仲裁视频会议H5

trtc.esm.js 449KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var rl=Object.create;var Sr=Object.defineProperty,sl=Object.defineProperties,vc=Object.getOwnPropertyDescriptor,ol=Object.getOwnPropertyDescriptors,nl=Object.getOwnPropertyNames,vs=Object.getOwnPropertySymbols,kc=Object.getPrototypeOf,dn=Object.prototype.hasOwnProperty,Mc=Object.prototype.propertyIsEnumerable,al=Reflect.get;var ks=Math.pow,cn=(r,i,e)=>i in r?Sr(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,N=(r,i)=>{for(var e in i||(i={}))dn.call(i,e)&&cn(r,e,i[e]);if(vs)for(var e of vs(i))Mc.call(i,e)&&cn(r,e,i[e]);return r},M=(r,i)=>sl(r,ol(i));var Lc=(r,i)=>{var e={};for(var t in r)dn.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&vs)for(var t of vs(r))i.indexOf(t)<0&&Mc.call(r,t)&&(e[t]=r[t]);return e};var Ir=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),Ar=(r,i)=>{for(var e in i)Sr(r,e,{get:i[e],enumerable:!0})},cl=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of nl(i))!dn.call(r,s)&&s!==e&&Sr(r,s,{get:()=>i[s],enumerable:!(t=vc(i,s))||t.enumerable});return r};var Ne=(r,i,e)=>(e=r!=null?rl(kc(r)):{},cl(i||!r||!r.__esModule?Sr(e,"default",{value:r,enumerable:!0}):e,r));var y=(r,i,e,t)=>{for(var s=t>1?void 0:t?vc(i,e):i,o=r.length-1,n;o>=0;o--)(n=r[o])&&(s=(t?n(i,e,s):n(s))||s);return t&&s&&Sr(i,e,s),s};var d=(r,i,e)=>(cn(r,typeof i!="symbol"?i+"":i,e),e);var At=(r,i,e)=>al(kc(r),e,i);var p=(r,i,e)=>new Promise((t,s)=>{var o=c=>{try{a(e.next(c))}catch(u){s(u)}},n=c=>{try{a(e.throw(c))}catch(u){s(u)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(r,i)).next())});var Me=Ir((Jm,un)=>{"use strict";var dl=Object.prototype.hasOwnProperty,Se="~";function Rr(){}Object.create&&(Rr.prototype=Object.create(null),new Rr().__proto__||(Se=!1));function ul(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function Pc(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new ul(e,t||r,s),n=Se?Se+i:i;return r._events[n]?r._events[n].fn?r._events[n]=[r._events[n],o]:r._events[n].push(o):(r._events[n]=o,r._eventsCount++),r}function Ms(r,i){--r._eventsCount===0?r._events=new Rr:delete r._events[i]}function Ee(){this._events=new Rr,this._eventsCount=0}Ee.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)dl.call(e,t)&&i.push(Se?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Ee.prototype.listeners=function(i){var e=Se?Se+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,o=t.length,n=new Array(o);s<o;s++)n[s]=t[s].fn;return n};Ee.prototype.listenerCount=function(i){var e=Se?Se+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Ee.prototype.emit=function(i,e,t,s,o,n){var a=Se?Se+i:i;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,s),!0;case 5:return c.fn.call(c.context,e,t,s,o),!0;case 6:return c.fn.call(c.context,e,t,s,o,n),!0}for(m=1,l=new Array(u-1);m<u;m++)l[m-1]=arguments[m];c.fn.apply(c.context,l)}else{var f=c.length,I;for(m=0;m<f;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),u){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,e);break;case 3:c[m].fn.call(c[m].context,e,t);break;case 4:c[m].fn.call(c[m].context,e,t,s);break;default:if(!l)for(I=1,l=new Array(u-1);I<u;I++)l[I-1]=arguments[I];c[m].fn.apply(c[m].context,l)}}return!0};Ee.prototype.on=function(i,e,t){return Pc(this,i,e,t,!1)};Ee.prototype.once=function(i,e,t){return Pc(this,i,e,t,!0)};Ee.prototype.removeListener=function(i,e,t,s){var o=Se?Se+i:i;if(!this._events[o])return this;if(!e)return Ms(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!s||n.once)&&(!t||n.context===t)&&Ms(this,o);else{for(var a=0,c=[],u=n.length;a<u;a++)(n[a].fn!==e||s&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:Ms(this,o)}return this};Ee.prototype.removeAllListeners=function(i){var e;return i?(e=Se?Se+i:i,this._events[e]&&Ms(this,e)):(this._events=new Rr,this._eventsCount=0),this};Ee.prototype.off=Ee.prototype.removeListener;Ee.prototype.addListener=Ee.prototype.on;Ee.prefixed=Se;Ee.EventEmitter=Ee;typeof un!="undefined"&&(un.exports=Ee)});var ac=Ir((_N,Iu)=>{var Su=Iu.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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:%d trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\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(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["network-cost"]!=null?" network-cost %d":"%v",i}},{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(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.value!=null&&(i+=":%s")),i}},{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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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:"invalid",names:["value"]}]};Object.keys(Su).forEach(function(r){var i=Su[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Cu=Ir($t=>{var _r=function(r){return String(Number(r))===r?Number(r):r},pm=function(r,i,e,t){if(t&&!e)i[t]=_r(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=_r(r[s+1]))},_m=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;pm(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Au=ac(),fm=RegExp.prototype.test.bind(/^([a-z])=(.*)/);$t.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(fm).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Au[o]||[]).length;a+=1){var c=Au[o][a];if(c.reg.test(n))return _m(c,t,n)}}),i.media=e,i};var Ru=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=_r(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};$t.parseParams=function(r){return r.split(/;\s?/).reduce(Ru,{})};$t.parseFmtpConfig=$t.parseParams;$t.parsePayloads=function(r){return r.toString().split(" ").map(Number)};$t.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(_r),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};$t.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Ru,{})})};$t.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=_r(e):(t=_r(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var yu=Ir((EN,Nu)=>{var cc=ac(),Em=/%[sdv%]/g,Tm=function(r){var i=1,e=arguments,t=e.length;return r.replace(Em,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Ss=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return Tm.apply(null,s)},gm=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Sm=["i","c","b","a"];Nu.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||gm,t=i.innerOrder||Sm,s=[];return e.forEach(function(o){cc[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(Ss(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(Ss(o,n,a))})})}),r.media.forEach(function(o){s.push(Ss("m",cc.m[0],o)),t.forEach(function(n){cc[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(Ss(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(Ss(n,a,c))})})})}),s.join(`\r
  2. `)+`\r
  3. `}});var dc=Ir(Ft=>{var ki=Cu(),Im=yu();Ft.write=Im;Ft.parse=ki.parse;Ft.parseFmtpConfig=ki.parseFmtpConfig;Ft.parseParams=ki.parseParams;Ft.parsePayloads=ki.parsePayloads;Ft.parseRemoteCandidates=ki.parseRemoteCandidates;Ft.parseImageAttributes=ki.parseImageAttributes;Ft.parseSimulcastStreamList=ki.parseSimulcastStreamList});import mk from"webrtc-adapter";var hu=Ne(Me());var xc=(v=>(v[v.INVALID_PARAMETER=4096]="INVALID_PARAMETER",v[v.INVALID_OPERATION=4097]="INVALID_OPERATION",v[v.NOT_SUPPORTED=4098]="NOT_SUPPORTED",v[v.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",v[v.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",v[v.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",v[v.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",v[v.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",v[v.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",v[v.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",v[v.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",v[v.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",v[v.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",v[v.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",v[v.CLIENT_BANNED=16448]="CLIENT_BANNED",v[v.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",v[v.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",v[v.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",v[v.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",v[v.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",v[v.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",v[v.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",v[v.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",v[v.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",v[v.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",v[v.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",v[v.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",v[v.API_CALL_ABORTED=16461]="API_CALL_ABORTED",v[v.UNKNOWN=65535]="UNKNOWN",v))(xc||{}),g=xc;var ll=function(r){for(let i in g)if(g[i]===r)return i;return"UNKNOWN"},ln=class extends Error{constructor({name:e="RtcError",message:t,code:s=g.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${ll(s)} 0x${s.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=s,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},C=ln;var wc=new Date().getTime(),hn=0,Vc=function(r){wc=r,hn=wc-new Date().getTime();let i=new Date;i.setTime(r),A.info(`baseTime from server: ${i} offset: ${hn}`)},Cr=function(){return new Date().getTime()+hn},Ls=function(){let r=new Date;return r.setTime(Cr()),r.toLocaleString()};var Ae={};Ar(Ae,{bytes2ms:()=>jl,copyProperties:()=>Jl,deepMerge:()=>lt,env:()=>Kt,fibonacci:()=>er,formatedTime:()=>th,getConstructorName:()=>uo,getContainerFromElement:()=>lo,getEnv:()=>Wl,getInternalVersion:()=>ql,getLoggerUrl:()=>Si,getMuteStateFromFlag:()=>Qt,getNetworkQuality:()=>zl,getNetworkType:()=>co,getOSType:()=>Qc,getReconnectionTimeout:()=>He,getStringByteLength:()=>ho,getSysInfo:()=>Kl,getTerminalType:()=>Yc,getTurnServer:()=>Zl,getValueType:()=>oe,glog:()=>zc,ipv4ToUint32:()=>zr,isArray:()=>de,isArrayOrObject:()=>Yr,isAudioWorkletSupported:()=>$n,isBoolean:()=>re,isConstructor:()=>qr,isEmpty:()=>Xr,isFunction:()=>j,isLangChinese:()=>ut,isMediaStreamTrack:()=>Ql,isNumber:()=>Q,isObject:()=>Ii,isOverseaSdkAppId:()=>ao,isPlainObject:()=>Fe,isPromise:()=>Qr,isRemoteTrack:()=>Yt,isString:()=>Y,isUndefined:()=>T,ms2bytes:()=>Yl,ms2samples:()=>Xc,performanceNow:()=>$,promiseAny:()=>Fn,samples2ms:()=>qc,stringify:()=>ze,stringifyIncludeValue:()=>Hn});var Kt={};Ar(Kt,{ANDROID_VERSION:()=>_n,CHROME_MAJOR_VERSION:()=>mi,CHROME_VERSION:()=>qs,EDGE_VERSION:()=>xs,EDG_MAJOR_VERSION:()=>En,EDG_VERSION:()=>ws,FIREFOX_MAJOR_VERSION:()=>fn,FIREFOX_VERSION:()=>Ps,HUAWEI_VERSION:()=>Js,IE_VERSION:()=>fl,IOS_MAIN_VERSION:()=>In,IOS_VERSION:()=>Wt,IPADQQB_VERSION:()=>Ws,IS_ANDROID:()=>Le,IS_ANDROID_WEBVIEW:()=>Sl,IS_ANY_SAFARI:()=>Sn,IS_CHROME:()=>Wi,IS_CHROME_OS:()=>Hc,IS_CHROMIUM_BASE:()=>Vr,IS_EDG:()=>$i,IS_EDGE:()=>Bi,IS_ELECTRON:()=>Tl,IS_FIREFOX:()=>X,IS_HEADLESS_CHROME:()=>gn,IS_HUAWEI:()=>gl,IS_HUAWEIBROWSER:()=>Lr,IS_IE:()=>Fc,IS_IE8:()=>_l,IS_IOS:()=>Je,IS_IOS_13_OR_14:()=>Il,IS_IOS_15_1:()=>Ur,IS_IPAD:()=>Ui,IS_IPADQQB:()=>vr,IS_IPAD_PRO:()=>pn,IS_IPHONE:()=>Gt,IS_IPOD:()=>$c,IS_LINUX:()=>kr,IS_LOCAL:()=>Ye,IS_MAC:()=>je,IS_MACQQB:()=>Dr,IS_MIBROWSER:()=>Mr,IS_MQQB:()=>Gi,IS_NATIVE_ANDROID:()=>pl,IS_OLD_ANDROID:()=>ml,IS_OPPOBROWSER:()=>xr,IS_SAFARI:()=>$e,IS_SAFARI_15_1:()=>An,IS_SAMSUNGBROWSER:()=>Pr,IS_SOGOU:()=>yr,IS_SOGOUM:()=>Nr,IS_TBS:()=>nt,IS_UCBROWSER:()=>Tn,IS_VIVOBROWSER:()=>wr,IS_WECHAT:()=>Fi,IS_WIN:()=>Rt,IS_WQQB:()=>Or,IS_WX:()=>El,IS_X5MQQB:()=>Hi,IS_XWEB:()=>br,MACQQB_VERSION:()=>Gs,MI_VERSION:()=>Ks,MQQB_VERSION:()=>Vi,OPPO_VERSION:()=>Ys,SAFARI_VERSION:()=>Ki,SAMSUNG_VERSION:()=>js,SOGOUM_VERSION:()=>Vs,SOGOU_VERSION:()=>Us,TBS_VERSION:()=>Bs,USER_AGENT:()=>Ke,VIVO_VERSION:()=>Qs,WECHAT_VERSION:()=>Fs,WQQB_VERSION:()=>Hs,XWEB_VERSION:()=>$s,browserInfo:()=>ot,getBrowserInfo:()=>Gc,getChromeMajorVersion:()=>at,getOSName:()=>Xs,getOSString:()=>Rn,getUserAgentData:()=>Br,isLocalStorageEnabled:()=>Ct});var Ke=typeof navigator=="undefined"?"":navigator.userAgent,H=r=>new RegExp(r,"i").test(Ke),le=r=>{if(H(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=Ke.match(i);if(e&&e[1])return e[1]}return""},mn=r=>{if(H(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=Ke.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Uc=/AppleWebKit\/([\d.]+)/i.exec(Ke),hl=Uc?parseFloat(Uc[1]):NaN,Ui=H("iPad"),pn=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&H("Macintosh"),Gt=H("iPhone")&&!Ui,$c=H("iPod"),Je=Gt||Ui||$c||pn,Le=H("Android"),_n=function(){if(Le){let r=Ke.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(r){let i=r[1]&&parseFloat(r[1]),e=r[2]&&parseFloat(r[2]);if(i&&e)return parseFloat(`${r[1]}.${r[2]}`);if(i)return i}}return NaN}(),ml=Le&&H("webkit")&&_n<2.3,pl=Le&&_n<5&&hl<537,X=H("Firefox"),Ps=le("Firefox"),fn=mn("Firefox"),Bi=H("Edge"),xs=le("Edge"),$i=H("Edg"),ws=le("Edg"),En=mn("Edg"),Nr=H("SogouMobileBrowser"),Vs=le("SogouMobileBrowser"),yr=H("MetaSr\\s"),Us=le("MetaSr\\s"),nt=H("TBS"),Bs=le("TBS"),br=H("XWEB"),$s=le("XWEB"),_l=H("MSIE\\s8\\.0"),Fc=H("MSIE\\/\\d+"),fl=function(){if(Fc){let r=/MSIE\s(\d+)\.\d/.exec(Ke),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(Ke)&&/rv:11.0/.test(Ke)&&(i=11),i}return NaN}(),Fi=H("(micromessenger|webbrowser)"),Fs=le("MicroMessenger"),Hi=!nt&&H("MQQBrowser")&&H("COVC"),Gi=!nt&&H("MQQBrowser")&&!H("COVC"),Vi=Gi||Hi?le("MQQBrowser"):"",Or=!nt&&H(" QQBrowser"),Hs=le(" QQBrowser"),Dr=!nt&&H("QQBrowserLite"),Gs=le("QQBrowserLite"),vr=!nt&&H("MQBHD"),Ws=le("MQBHD"),Rt=H("Windows"),je=!Je&&H("MAC OS X"),kr=!Le&&H("Linux"),Hc=H("CrOS"),El=H("MicroMessenger"),Tn=H("UCBrowser"),Tl=H("Electron"),Mr=H("MiuiBrowser"),Ks=le("MiuiBrowser"),Lr=H("HuaweiBrowser"),gl=H("Huawei"),Js=le("HuaweiBrowser"),Pr=H("SamsungBrowser"),js=le("SamsungBrowser"),xr=H("HeyTapBrowser"),Ys=le("HeyTapBrowser"),wr=H("VivoBrowser"),Qs=le("VivoBrowser"),at=()=>mn("Chrome"),Vr=H("Chrome"),Wi=!Bi&&!yr&&!Nr&&!nt&&!br&&!$i&&!Or&&!Mr&&!Lr&&!Pr&&!xr&&!wr&&Vr,gn=H("HeadlessChrome"),mi=at(),qs=le("Chrome"),$e=!Vr&&!Gi&&!Hi&&!Dr&&!vr&&H("Safari"),Sn=$e||Je,Ki=le("Version"),Sl=/Android.*(wv|.0.0.0)/.test(Ke),Wt=(()=>{if(pn)return Ki;if(Je){let r=Ke.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),In=Number(Wt.split(".")[0]),An=Ki==="15.1",Ur=Wt==="15.1",Il=(()=>{let r=Number(Wt.split(".")[0]);return r===14||r===13})(),Ye=typeof location!="undefined"?location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1":!1,Ct=(()=>{let r;return()=>{if(T(r))try{r=!!window.localStorage}catch(i){r=!1}return r}})(),ot=Gc();function Gc(){let r=new Map([[X,["Firefox",Ps]],[$i,["Edg",ws]],[Wi,["Chrome",qs]],[$e,["Safari",Ki]],[nt,["TBS",Bs]],[br,["XWEB",$s]],[Fi&&Gt,["WeChat",Fs]],[Or,["QQ(Win)",Hs]],[Gi,["QQ(Mobile)",Vi]],[Hi,["QQ(Mobile X5)",Vi]],[Dr,["QQ(Mac)",Gs]],[vr,["QQ(iPad)",Ws]],[Mr,["MI",Ks]],[Lr,["HW",Js]],[Pr,["Samsung",js]],[xr,["OPPO",Ys]],[wr,["VIVO",Qs]],[Bi,["EDGE",xs]],[Nr,["SogouMobile",Vs]],[yr,["Sogou",Us]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var ye=null;function Br(){return p(this,null,function*(){if(ye)return ye;if(!navigator.userAgentData||!j(navigator.userAgentData.getHighEntropyValues))return null;try{return ye=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ye}catch(r){return null}})}var Bc=new Map([[Le,"Android"],[Je,"iOS"],[Rt,"Windows"],[je,"MacOS"],[kr,"Linux"],[Hc,"ChromeOS"]]),Xs=function(){return Bc.get(!0)?Bc.get(!0):ye?ye.platform:"unknown"},Rn=()=>{let r=Xs();return r+=`/${ot.name}/${$e?ot.version:ot.version.split(".")[0]}`,ye!=null&&ye.platformVersion&&(r+=`/${ye.platformVersion}`),ye!=null&&ye.architecture&&(r+=`/${ye.architecture}`),r};var Bn={};Ar(Bn,{AUDIO_MUTE_BIT:()=>ro,AUDIO_STAT_BIT:()=>Yi,AUX_STAT_BIT:()=>Hr,AUX_STREAM_MSID:()=>kn,BACKEND_ENV:()=>io,BASE_DOC_URL:()=>ct,BASE_HOST:()=>zs,CAPABILITIES_KEYS:()=>no,CLASS_NAME:()=>Bl,CLOUD_CONSOLE_URL:()=>Rl,DATA_FREEZE_TIMING:()=>oo,DOC_URL:()=>Cl,DTLS_STATE_UNKNOWN:()=>qe,ENV_NAME:()=>Nt,EXCHANGE_SDP_TIMEOUT:()=>wn,INTERVAL:()=>gi,IS_WORKER:()=>Ji,IS_WORKLET:()=>$r,KIBANA_EVENT:()=>be,LOCAL_STREAM_PUBLISH_STATE:()=>Jc,LOGGER_CMD_TYPE:()=>fi,LOGGER_DOMAIN:()=>bn,LOGGER_DOMAIN_OVERSEA:()=>On,LOG_LEVEL:()=>Qe,LOG_LEVEL_NAME:()=>Fl,MAIN_STREAM_MSID:()=>Gr,MICROPHONE_COMMUNICATIONS:()=>$l,MICROPHONE_DEFAULT:()=>Ti,NAME:()=>h,NETWORK_TYPE:()=>Jt,NOT_SUPPORTED_H264:()=>Ei,PAUSED_RETRY_COUNT:()=>Vn,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Kr,PEER_CONNECTION_STATE:()=>te,PEER_LEAVE_REASON:()=>Un,RAF:()=>jr,RECOVER_CAPTURE_INTERVAL:()=>zi,REMOTE_STREAM_TYPE_AUX:()=>Ln,REMOTE_STREAM_TYPE_MAIN:()=>Mn,RENDER_FREEZE_TIMING:()=>xl,RIC:()=>dt,SCHEDULE_DOMAIN:()=>qi,SCHEDULE_TIMEOUT:()=>Ul,SDP_SEMANTICS_PLAN_B:()=>Qi,SDP_SEMANTICS_UNIFIED_PLAN:()=>jt,SECOND_HOST:()=>Nn,SIGNAL_PING_PONG_INTERVAL:()=>yl,SIGNAL_PING_TIMEOUT:()=>Nl,SIGNAL_RECONNECTION_COUNT:()=>Wr,SMALL_STAT_BIT:()=>vn,SPEAKER_DEFAULT:()=>Jr,STORAGE_EXPIRES_TIME:()=>Zs,STREAM_TYPE_BIG:()=>wl,STREAM_TYPE_SMALL:()=>Vl,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Xi,SYNC_USER_LIST_INTERVAL:()=>Pl,Scene:()=>bt,Switch:()=>Wc,THIRD_HOST:()=>yn,TIMEOUT:()=>Zi,TRANSPORT_DIRECTION:()=>K,TRTC_ERROR_ASSISTANCE:()=>Dn,TRTC_QUALITY_BAD:()=>kl,TRTC_QUALITY_DISCONNECTED:()=>Ll,TRTC_QUALITY_EXCELLENT:()=>Ol,TRTC_QUALITY_GOOD:()=>Dl,TRTC_QUALITY_POOR:()=>vl,TRTC_QUALITY_UNKNOWN:()=>bl,TRTC_QUALITY_VERY_BAD:()=>Ml,UPDATE_OFFER_TIMEOUT:()=>xn,VIDEO_MUTE_BIT:()=>so,VIDEO_STAT_BIT:()=>ji,audioProfileMap:()=>eo,getRetryCount:()=>Ot,getScriptDir:()=>Al,innerVersion:()=>pi,loggerProxy:()=>Fr,screenProfileMap:()=>to,setLoggerProxy:()=>_i,setRetryCount:()=>Pn,setVersion:()=>Cn,version:()=>Ie,videoProfileMap:()=>yt});var pi="4.15.00.1600",Ie="5.0.0";function Cn(r){Ie=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));pi=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Ji=typeof importScripts!="undefined",$r=typeof registerProcessor!="undefined",Al=()=>{let r=Ji?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},Fr="",_i=r=>Fr=r,zs="web.sdk.qcloud.com",Nn="web.sdk.tencent.cn",yn="web.sdk.cloud.tencent.cn",Rl="https://console.cloud.tencent.com/trtc",ct=`https://${zs}/trtc/webrtc/v5/doc`,Cl=`${ct}/zh-cn/`,bn="https://yun.tim.qq.com",On="https://apisgp.my-imcloud.com",Dn="trtc_error_assistance",fi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},Nt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Qe=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(Qe||{}),Nl=18e3,yl=2e3,Jt={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},Zs=7*24*3600*1e3,Wc=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(Wc||{}),eo={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},yt={"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}},to={"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}},h={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"},K={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},io={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},bt=(e=>(e.LIVE="live",e.RTC="rtc",e))(bt||{}),ji=1,vn=2,Hr=4,Yi=8,ro=64,so=16,Gr="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",kn="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Mn=h.MAIN,Ln=h.AUXILIARY,bl=0,Ol=1,Dl=2,vl=3,kl=4,Ml=5,Ll=6,qe="unknown",te={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Kc=1/0;function Pn(r){Kc=r}function Ot(){return Kc}var Wr=30,be={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"},Pl=1e4,xn=1e4,wn=1e4,jt="unified-plan",Qi="plan-b",Ei=1028,Jc=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Jc||{}),oo=500,xl=1e3,wl=h.BIG,Vl=h.SMALL,Kr=10*1e3,qi={MAIN:"schedule.rtc.qq.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},Ul=2e3,Bl={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Vn=5,Ti="default",Jr=Ti,$l="communications",Fl=Object.keys(Qe),Un=["normal leave","timeout leave","kick","role change"],Xi=10,zi=2e3,dt="ric",jr="raf",gi="interval",Zi="timeout",no=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId"];var Xe=1e8;var Gl="trtc_env",Wl=function(){return new URLSearchParams(location.search).get(Gl)||""},ao=r=>Number(r)<14e8,Si=function(r,i){let e;Fr?e=Fr:e=ao(r)?On:bn;let t=Math.floor(Math.random()*ks(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`};function Yc(){return Le?4:Gt?2:Ui?3:je?12:Rt?5:kr?13:1}function Qc(){return Le?"Android":Gt?"iPhone":Ui?"iPad":je?"Mac":Rt?"Windows":kr?"Linux":"unknown"}function co(){let{userAgent:r,connection:i}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),s=i&&i.effectiveType&&i.effectiveType.toLowerCase();s==="slow-2"&&(s="2g");let o=e||"unknown";if(t)switch(t){case"cellular":case"wimax":o=s||"unknown";break;case"wifi":o="wifi";break;case"ethernet":o="wired";break;case"none":case"other":case"unknown":default:o="unknown";break}return o}var Kl=function(r){return{AbilityOption:{AVLimit:r,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Yc(),uint32_device_type:0,str_os_verion:Qc(),uint32_link_type:1,str_client_version:pi,uint32_net_type:Jt[co()],ua:navigator.userAgent,version:""}}}};function Jl(r,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(r,e,t)}return r}function jl(r,i=48e3){return qc(r/4,i)}function qc(r,i=48e3){return r*1e3/i}function Yl(r,i=48e3){return Xc(r,i)*4}function Xc(r,i=48e3){return r*i/1e3}var zc=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},ut=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Fe=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function er(r,i=1,e=1){return r<=1?e:er(r-1,e,i+e)}function He(r){return r>8?30*1e3:er(r)*1e3}function oe(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var j=r=>typeof r=="function",T=r=>typeof r=="undefined",Y=r=>typeof r=="string",Q=r=>typeof r=="number",re=r=>typeof r=="boolean",Ii=r=>oe(r)==="object",de=r=>oe(r)==="array",Ql=r=>oe(r)==="MediaStreamTrack".toLowerCase(),Yt=r=>r.isRemote,Qr=r=>oe(r)==="promise",qr=r=>j(r)&&r.prototype.constructor===r,uo=r=>qr(r)?r.prototype.constructor.name:"",$n=typeof AudioWorkletNode!="undefined";function Fn(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(o=>{t.push(o),t.length===r.length&&e(t)})})})}function $(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var jc=r=>+r<10?`0${r}`:r,ql=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=jc(e[1])+jc(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Xl=Object.prototype.hasOwnProperty,{toString:sp}=Object.prototype;function Xr(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Fe(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(Xl.call(r,i))return!1;return!0}}return!1}function Qt(r,i){return{userId:i,hasAudio:!!(r&Yi),hasVideo:!!(r&ji),hasAuxiliary:!!(r&Hr),hasSmall:!!(r&vn),audioMuted:!!(r&ro),videoMuted:!!(r&so),audioAvailable:!!(r&Yi)&&!(r&ro),videoAvailable:!!(r&ji)&&!(r&so)}}function zl(r,i){return r>50||i>500?5:r>30||i>350?4:r>20||i>200?3:r>10||i>100?2:r>=0||i>=0?1:0}function Zl(r){let i={urls:`turn:${r.url}`};return!T(r.username)&&!T(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",T(r.credentialType)||(i.credentialType=r.credentialType)),i}function zr(r,i=!0){if(!Y(r))return 0;let e=r.split(".");return i?(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 Yr=function(r){return de(r)||Ii(r)},lt=function(r,i,e,t){if(!(Yr(r)&&Yr(i)))return 0;let s=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(T(i[n])||e&&e.includes(n)))if(Yr(r[n])&&Yr(i[n]))s+=lt(r[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;r[n]!==i[n]&&(r[n]=i[n],s+=1)}return s},lo=r=>Y(r)?document.getElementById(r):r,eh=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),th=()=>eh.format(new Date);function ze(r,{keysToInclude:i,keysToExclude:e}){try{if(de(r))return`[${r.map(n=>ze(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Fe(r)||!de(i)&&!de(e))return JSON.stringify(r);let t={},s=new Set(i),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(t[n]=Fe(r[n])||de(r[n])?JSON.parse(ze(r[n],{keysToExclude:e,keysToInclude:i})):r[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Hn(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),ze(r,{keysToInclude:e})}function ho(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}function qt({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((o,n)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);o({data:a})}catch(a){o({data:s.response})}else n({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}var ih=0,rh=1,Zc=2;function sh({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:u=1e3}=i,l=0,m=-1,f=ih,I=(b,k)=>p(this,null,function*(){let ie=n||this;try{let fe=yield r.apply(ie,a);l>0&&o&&o.call(this,l),l=0,b(fe)}catch(fe){let ui=()=>{clearTimeout(m),l=0,f=Zc,k(fe)},li=()=>{f!==Zc&&l<(j(c)?c():c)?(l++,f=rh,j(t)&&t.call(this,l,ui),m=window.setTimeout(()=>{m=-1,I(b,k)},j(u)?u(l):u)):(ui(),j(s)&&s.call(this,fe))};j(e)?e.call(this,{error:fe,retry:li,reject:k,retryFuncArgs:a,retryCount:l}):li()}});return new Promise(I)}}var ht=sh;var tr=class{constructor(i){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=re(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),A.log(i,e,T(this.userId)||Xr(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var ed=Ne(Me(),1),oh=new ed.default,E=oh;var ir=(V=>(V.ROOM_DESTROY="1",V.JOIN_START="21",V.JOIN_SCHEDULE_SUCCESS="22",V.JOIN_SIGNAL_CONNECTION_START="23",V.JOIN_SIGNAL_CONNECTION_END="24",V.JOIN_SEND_CMD="25",V.JOIN_RECEIVED_CMD_RES="26",V.JOIN_SUCCESS="27",V.JOIN_FAILED="28",V.LEAVE_START="51",V.LEAVE_SEND_CMD="52",V.LEAVE_SUCCESS="53",V.PUBLISH_START="61",V.SEND_FIRST_VIDEO_FRAME="62",V.PUBLISH_FAILED="63",V.SUBSCRIBE_START="81",V.SUBSCRIBE_SUCCESS="82",V.SUBSCRIBE_FAILED="84",V.UNSUBSCRIBE_SUCCESS="83",V.LOCAL_TRACK_CAPTURE_START="101",V.LOCAL_TRACK_CAPTURE_SUCCESS="102",V.LOCAL_TRACK_CAPTURE_FAILED="103",V.LOCAL_TRACK_PUBLISHED="104",V.LOCAL_TRACK_UNPUBLISHED="105",V.LOCAL_TRACK_REPLACED="106",V.SWITCH_DEVICE_SUCCESS="107",V.TRACK_MUTED="108",V.TRACK_UNMUTED="109",V.REMOTE_TRACK_SUBSCRIBED="110",V.REMOTE_TRACK_UNSUBSCRIBED="111",V.PLAY_TRACK_START="151",V.PLAYER_STATE_CHANGED="152",V.VIDEO_LOADED_DATA="153",V.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",V.WORKLET_LOADED_SUCCESS="155",V.WORKLET_LOADED_FAILED="156",V.SIGNAL_CONNECTION_STATE_CHANGED="201",V.PEER_CONNECTION_STATE_CHANGED="202",V.SINGLE_CONNECTION_STAT="203",V.HEARTBEAT_REPORT="251",V.RECEIVED_PUBLISHED_USER_LIST="252",V.REMOTE_PUBLISH_STATE_CHANGED="253",V.AUDIO_LEVEL_INTERVAL="260",V.NETWORK_QUALITY="261",V.API_SUCCESS_RATE="262",V))(ir||{});var _=ir;var nh="%cTRTC%c%s",ah="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ch="display: inline",dh=!(Je||Le||gn),Gn=class{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Ji&&!$r&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){E.on(_.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&Qe[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),E.on(_.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),E.once(_.JOIN_FAILED,()=>{this.startUpload()}),E.on(_.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:o})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})});else if(Y(t.userId)&&Q(t.sdkAppId)){let{userId:s,sdkAppId:o}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let s=[...i.values()];for(let o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:c}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Ls(),sdkAppId:String(a),userId:n,version:Ie,log:c.map(u=>u.log).join(`
  4. `)}),a),c.forEach(u=>u.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return ht({retryFunction:()=>qt({url:Si(e,fi.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(Cr());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${Qe[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(Qe[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(Y(i))return i;try{return JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,o){var a;if(e.unshift(this.getPrefix(i)),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,u)=>`${c} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:s,sdkAppId:o,forAllJoinedClients:t}),i<this._logLevel)return;let n=((a=Qe[i])==null?void 0:a.toLowerCase())||"info";dh?console[n](nh,ah,ch,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new tr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Qe[t]&&(this._logLevelToUpload=t)}},A=new Gn;var uh=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let i=Math.random()*16|0;return(r=="x"?i:i&3|8).toString(16)})},Wn=uh;var Kn=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Ct())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=JSON.parse(localStorage.getItem(t));if(s&&s.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!Ct())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){A.warn(i)}}getItem(i){if(!Ct())return null;try{let e=JSON.parse(localStorage.getItem(this.getRealKey(i)));return e&&e.expiresIn>=Date.now()?e.value:null}catch(e){A.warn(e)}}setItem(i,e){if(!!Ct())try{let t={expiresIn:Date.now()+Zs,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){A.warn(t)}}deleteItem(i){if(!Ct())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return A.warn(e),!1}}clear(){if(!!Ct())try{localStorage.clear()}catch(i){A.warn(i)}}},rr=new Kn;var Dt={};Ar(Dt,{HTTPS_API:()=>fh,IS_GET_CAPABILITIES_SUPPORTED:()=>Yn,IS_GET_SETTINGS_SUPPORTED:()=>tt,IS_SEI_SUPPORTED:()=>Zt,IS_SPC_SUPPORTED:()=>es,basis:()=>Sh,checkSystemRequirementsInternal:()=>jn,decodeSupportStatus:()=>po,encodeSupportStatus:()=>sd,getBrowserInfo:()=>mh,getDisplayResolution:()=>od,isAddTransceiverSupported:()=>et,isBrowserSupported:()=>Jn,isGetReceiversSupported:()=>Ai,isGetSendersSupported:()=>sr,isGetTransceiversSupported:()=>mt,isGetUserMediaSupported:()=>nd,isMediaDevicesSupported:()=>mo,isMediaSessionSupported:()=>ud,isMediaStreamTrackProcessorSupported:()=>ph,isReplaceTrackSupported:()=>gh,isScreenCaptureApiAvailable:()=>Zr,isSelectedCandidatePair:()=>zt,isSetParametersSupported:()=>ts,isSmallStreamAPISupported:()=>cd,isSmallStreamSupported:()=>_o,isStopTransceiverSupported:()=>Th,isTRTCSupported:()=>_h,isUnifiedPlanDefault:()=>Eh,isUsedInHttpProtocol:()=>Xt,isWebAudioSupported:()=>ad,isWebCodecSupported:()=>dd,isWebCodecsSupported:()=>rd,isWebRTCSupported:()=>Qn,isWebTransportSupported:()=>ld});var O={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_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",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"},me={AVOID_REPEATED_CALL(r){return`previous ${r.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${oe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${oe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:r,rule:i,fnName:e,value:t}){return`the min value of ${r||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:r,rule:i,fnName:e,value:t}){return`the max value of ${r||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(r){return`${r.commandDesc||r.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(r){return`SignalChannel setup failure: (errorCode: ${r.errorCode}, errorMsg: ${r.errorMsg} }).`},ERROR_MESSAGE(r){let i=`${r.type} failed`;return r.message&&(i=`${i}: ${r.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(r){return`exchange sdp failed ${r.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(r){return`'${r}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(r){return`'${r}' 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:r,code:i}){return`Failed to join room - ${r} code: ${i}`},REJOIN_ROOM_FAILED(r){return`reJoin room: ${r.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(r){return`duplicate ${r} stream publishing, please unpublish your prev ${r} 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:r,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${r}.`},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(r){return`switchRole failed, errCode: ${r.code} errMsg: ${r.message}.`},CLIENT_BANNED(r){return`client was banned because of ${r.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(r){return`startPublishCDNStream failed, errMsg: ${r.message}.`},STOP_PUBLISH_CDN_FAILED(r){return`stopPublishCDNStream failed, errMsg: ${r.message}.`},INVALID_STREAM_ID(r){return`'${r}' 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(r){return`cannot replace ${r.kind} track because stream has not ${r.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(r){return`startMixTranscode failed, errMsg: ${r.message}.`},STOP_MIX_TRANSCODE_FAILED(r){return`stopMixTranscode failed, errMsg: ${r.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:r,rule:i,fnName:e,value:t}){return`'${r||i.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(r){return`'${r}' 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:r,fnName:i})=>`'${r}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:r,fnName:i,type:e})=>`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:r=>`${r.media} play failed\uFF0Cbrowser exception: ${r.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(r){return`${r}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(r){return`${r.signalResponse} failed, response code is ${r.code} , errMsg: ${r.message}.`},CATCH_HANDLER_ERROR({name:r,event:i}){return`an error was caught on ${r}.on('${i}', handler), please check your code on 'handler'.`},API_NOT_EXIST({name:r}){return`experimental api ${r} does not exist.`},REPEAT_JOIN:r=>`[${r}] is calling client.join api or has already joined room, 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:r}){return`failed to call ${r}() because client was destroyed.`},SEI_NOT_SUPPORT:r=>`not support to sendSEIMessage${r===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:r=>`buffer size(${r}) is over 1000 Bytes`,SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:r,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${r?"size":"times"} is over ${r?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(r){return`connection aborted due to: ${r}`},API_CALL_ABORTED(r){let i;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${r.userId} ${r.streamType} stream aborted, reason: remote user ${r.userId} unpublished stream.`:i=`API aborted, reason: ${r.message}`,i},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:r=>`'streamType' is required when 'userId' is not '*', calling ${r}()`};var td=(r,i)=>i?`${ct}/${r}/${i}`:`${ct}/${r}/index.html`;var lh=()=>{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 r=localStorage.getItem(Dn);if(r){r=JSON.parse(r);let i=document.createElement("script");i.type="text/javascript",i.text=r.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function D(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,o="",n="",a="";j(me[i])?o=me[i](e):Y(me[i])&&(o=me[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:u}=lh();t?a=`${t.className}.html#${t.fnName}`:u&&u[i]&&(j(u[i])?a=u[i](e):Y(u[i])&&(a=u[i]));let l=o;return ut()&&(c&&c[i]&&(j(c[i])?n=c[i](e):Y(c[i])&&(n=c[i])),n&&(s?l=`${n}
  5. \u8BF7\u67E5\u770B\u6587\u6863: ${td("zh-cn",a)}
  6. `:l=`${n}
  7. `,l+=o)),s&&(l+=`
  8. Refer to: ${td("en",a)}
  9. `),l}var z={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},hh=new Map([[X,["Firefox",Ps]],[$i,["Edg",ws]],[Wi,["Chrome",qs]],[$e,["Safari",Ki]],[nt,["TBS",Bs]],[br,["XWEB",$s]],[Fi&&Gt,["WeChat",Fs]],[Or,["QQ(Win)",Hs]],[Gi,["QQ(Mobile)",Vi]],[Hi,["QQ(Mobile X5)",Vi]],[Dr,["QQ(Mac)",Gs]],[vr,["QQ(iPad)",Ws]],[Mr,["MI",Ks]],[Lr,["HW",Js]],[Pr,["Samsung",js]],[xr,["OPPO",Ys]],[wr,["VIVO",Qs]],[Bi,["EDGE",xs]],[Nr,["SogouMobile",Vs]],[yr,["Sogou",Us]]]);function mh(){let r=hh.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var Jn=function(){return!(Tn||Bi||$i&&En<80||X&&fn<56)},rd=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},mo=function(){if(!navigator.mediaDevices)return Xt()||A.error(me.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},id=!1;function Xt(){return location.protocol==="http:"&&!Ye?(id||A.error(D({key:O.NOT_SUPPORTED_HTTP})),id=!0,!0):!1}var ph=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},sd=function(){return p(this,null,function*(){if(z.detail.isH264EncodeSupported||z.detail.isVp8EncodeSupported)return{isH264EncodeSupported:z.detail.isH264EncodeSupported,isVp8EncodeSupported:z.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),z.detail.isH264EncodeSupported=i,z.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:z.detail.isH264EncodeSupported,isVp8EncodeSupported:z.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},po=function(){return p(this,null,function*(){if(z.detail.isH264DecodeSupported&&z.detail.isVp8DecodeSupported)return{isH264DecodeSupported:z.detail.isH264DecodeSupported,isVp8DecodeSupported:z.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},jn=function(){return p(this,null,function*(){if(z.result)return z;let r=Jn(),i=Qn(),e=rd(),t=mo(),{isH264EncodeSupported:s,isVp8EncodeSupported:o}=yield sd(),{isH264DecodeSupported:n,isVp8DecodeSupported:a}=yield po();return z.result=r&&i&&t&&(s||o)&&(n||a),z.detail.isBrowserSupported=r,z.detail.isWebRTCSupported=i,z.detail.isWebCodecsSupported=e,z.detail.isMediaDevicesSupported=t,z.detail.isScreenShareSupported=Zr(),z.detail.isSmallStreamSupported=_o(),z.detail.isH264EncodeSupported=s,z.detail.isVp8EncodeSupported=o,z.detail.isH264DecodeSupported=n,z.detail.isVp8DecodeSupported=a,z.result||A.error(`${navigator.userAgent} ${Hn(z.detail,!1)}`),z})},_h=function(){return z.result},Zr=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},fh=(r,i,e)=>{location.protocol==="http:"&&!Ye&&(r[i]=()=>{throw new C({code:g.INVALID_OPERATION,message:me.NOT_SUPPORTED_HTTP})})},zt=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(re(r.selected)&&!r.selected):!1};function od(){let r="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${i} * ${e}`}return r}function nd(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ad(){let r={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){r.isSupported=!0;break}return r.isSupported}function cd(){return"captureStream"in HTMLCanvasElement.prototype}function _o(){return Fi||Je||mi&&mi<63?!1:!!(Jn()&&cd())}var Eh=function(){if(T(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:jt}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function Ai(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function sr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function mt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function et(){return In===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var es=(()=>!(!et()||Vr&&mi<74))();function Th(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function gh(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function ts(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&sr()}var tt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Yn=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Zt="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&at()>=86,Qn=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function dd(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(r.AudioDecoder=!0),T(window.AudioEncoder)||(r.AudioEncoder=!0),T(window.VideoDecoder)||(r.VideoDecoder=!0),T(window.VideoEncoder)||(r.VideoEncoder=!0),T(window.ImageDecoder)||(r.ImageDecoder=!0),r}function ud(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function ld(){return!T(window.WebTransport)}function Sh(){let r={browser:`${ot.name}/${ot.version}`,os:Xs(),displayResolution:od(),isScreenShareSupported:Zr(),isWebRTCSupported:Qn(),isGetUserMediaSupported:nd(),isWebAudioSupported:ad(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:dd(),isMediaSessionSupported:ud(),isWebTransportSupported:ld()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var md=Ne(Me(),1);var hd=Symbol("instance"),Qp=Symbol("abortCtrl"),qn=Symbol("cacheResult"),Ri=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,ss.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},is=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Ih(r){return typeof r=="object"&&r&&"then"in r}var rs=new Map;function ee(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=rs.get(t)||[];rs.has(t)||rs.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let u=this;if(e.context&&(u=L.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),u.state===i)return u[qn];u.state instanceof Ri&&u.state.action==e.abortAction&&u.state.abort(u);let l=null;if(Array.isArray(r)?r.length==0?u.state instanceof Ri&&u.state.abort(u):(typeof u.state!="string"||!r.includes(u.state))&&(l=new is(u._state,`${u.name} ${n} to ${i} failed: current state ${u._state} not in from config`)):r!==u.state&&(l=new is(u._state,`${u.name} ${n} to ${i} failed: current state ${u._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=u.state,f=new Ri(m,i,n);ss.call(u,f);let I=k=>{var ie;return u[qn]=k,f.aborted||(ss.call(u,i),(ie=e.success)===null||ie===void 0||ie.call(this,u[qn])),k},b=k=>{let ie=k instanceof Error?k.message:String(k);if(ss.call(u,m,k),e.fail)e.fail.call(this,new is(u._state,`action '${n}' failed :${ie}`,k instanceof Error?k:new Error(ie)));else{if(e.ignoreError)return k;throw k}};try{let k=a.apply(this,c);return Ih(k)?k.then(I).catch(b):I(k)}catch(k){b(k)}}}}var Ah=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function ss(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(L.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var L=class extends md.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=L.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[hd];s?this.name=s.name+"-"+s.count++:t[hd]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=rs.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);rs.has(a)&&(a.stateDiagram.forEach(u=>t.add(u)),a.allStates.forEach(u=>n.add(u))),e.forEach(({from:u,to:l,action:m})=>{typeof u=="string"?s.push({from:u,to:l,action:m}):u.length?u.forEach(f=>{s.push({from:f,to:l,action:m})}):o.push({to:l,action:m})}),s.forEach(({from:u,to:l,action:m})=>{n.add(u),n.add(l),n.add(m+"ing"),t.add(`${u} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${u} : ${m} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{t.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),n.forEach(m=>{m!==u&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=L.instances.get(i),e||L.instances.set(i,e=new L(i,void 0,Object.create(L.prototype)))):(e=L.instances2.get(i),e||L.instances2.set(i,e=new L(i.constructor.name,void 0,Object.create(L.prototype)))),e}static getState(i){var e;return(e=L.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Ah(L.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){ss.call(this,i)}};L.STATECHANGED="stateChanged";L.UPDATEAFSM="updateAFSM";L.INIT="[*]";L.ON="on";L.OFF="off";L.instances=new Map;L.instances2=new WeakMap;var pd=(window==null?void 0:window.requestIdleCallback)||function(r){let i=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},Rh=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Ch=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),os=class{static generateTaskID(){return this.currentTaskID++}static run(i=Zi,e,t){i===gi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===dt?t=N({delay:1e4,count:0},t):i===jr?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),Ii(e)&&(t=N(N({},t),e)),j(i)&&(e=i,i=Zi);let s=N({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(s.taskID,s),this[i](s),s.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.delay=(1e3/i.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
  10. let timerID = null;
  11. self.onmessage = function (e) {
  12. if (e.data === 'start') {
  13. timerID = setInterval(() => {
  14. self.postMessage('tick');
  15. }, ${i.delay});
  16. } else if (e.data === 'stop') {
  17. clearInterval(timerID);
  18. }
  19. };
  20. `])));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=$(),t,s=()=>{if(t=$()-e,t>=i.delay&&(e=$()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=pd(s,{timeout:i.delay})};return i.ricID=pd(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=$(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=$()-e,e=$(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=$()-e,t>=i.delay&&(e=$()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let o=()=>{if(document.hidden){let n=$()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Ch(s),o&&Rh(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};os.taskMap=new Map,os.currentTaskID=1;var Z=os;var t_={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:h.SEI_MESSAGE,ERROR:"error"};var pt={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};var Xn=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Ie,env:Nt.QCLOUD,browserVersion:ot.name+ot.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:s}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(s))}logSuccessEvent(i){Ye||!A.isAbleToUpload||this._configs.env===Nt.QCLOUD&&this.uploadEventToKibana(M(N({},i),{result:"success"}))}logFailedEvent(i){if(Ye||!A.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||g.UNKNOWN};this._configs.env===Nt.QCLOUD&&this.uploadEventToKibana(M(N({},n),{error:s}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let s={timestamp:Ls(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Ie,log:i};t&&(s.errorInfo=t.message),this.sendRequest(Si(this._configs.sdkAppId,fi.LOG),s)}sendRequest(i,e){if(!A.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}qt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},q=new Xn;var vt="trtc_autoplay",zn=`${vt}_mask`,or=`${vt}_wrapper`,_d=`${vt}_header`,Zn=`${vt}_content`,fo=`${vt}_action_wrapper`,ea=`${vt}_question`,ta=`${vt}_collapse`,Eo=`${vt}_action_confirm`,fd=`${vt}_detail`,Ed="#2473E8",ra="dialog",Nh=`${ra}-show`,yh=`${ra}-1`,bh=`${ra}-2`,Td=!1,sa=()=>!!document.querySelector(`.${or}`),Sd=`${ct}/${ut()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,gd=`<br><a href='${Sd}' target='_blank'>${ut()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Oh=`${ut()?`\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${gd}`:`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. ${gd}`}`,ia=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(ut()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Td){let i=document.createElement("style");i.innerHTML=`.${zn}{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;}.${zn} div:not(.${fo}){display:block !important;}.${or}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${or} a{color:${Ed};}.${_d}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Zn}{margin:8px 0;}.${fo}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${ta}{margin-right:auto;cursor:pointer}.${ea}{height:100%;line-height:16px;cursor:pointer;}.${Eo}{margin-left:8px;color:#fff;background:${Ed};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Eo}:hover{opacity:0.9;}.${ta},.${Eo},.${Zn},.${ea}{font-size:14px;}@media screen and (max-width:750px){.${or}{width:80vw;}}`,document.head.appendChild(i),Td=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${zn}"><div class='${or}'><div class='${_d}'>${location.host}</div><div class='${Zn}'>${this.content}</div><div class='${fd}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Oh}</div><div class='${fo}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Eo,e.innerText=ut()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=ea,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
  21. <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">
  22. <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"/>
  23. <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"/>
  24. <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"/>
  25. </svg>
  26. `,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=ta,s.innerText=`${ut()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${fo}`);return n.appendChild(s),n.appendChild(t),n.appendChild(e),o}addDiaLog(){sa()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${or}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),q.uploadEvent({log:Nh}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){A.warn("confirm clicked, try resume stream"),E.emit(_.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${fd}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||q.uploadEvent({log:yh}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Sd,"_blank"),this._isQuestionClicked||q.uploadEvent({log:bh}),this._isQuestionClicked=!0}},Id=ia;var kt={};Ar(kt,{create:()=>Te,remove:()=>ne});var ns=new WeakMap;function Te(r,i){ns.has(r)||ns.set(r,[]);let e=ns.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function ne(r){let i=ns.get(r);i&&(i.forEach(e=>e()),ns.delete(r))}var Mt=class extends L{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"container",null);d(this,"mediaStream",new MediaStream);d(this,"track");d(this,"url");d(this,"attr");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=Vn,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return this._state==="PLAYING"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(pt.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element))){let t=new MediaStream;t.addTrack(e),this.element.srcObject=t}}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))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return p(this,null,function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=D({key:O.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new C({code:g.PLAY_NOT_ALLOWED,message:t})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(h.ENDED),this._interval>0&&Z.clearTask(this._interval)}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this.isPlaying?Promise.resolve():Ur?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,t){this.element&&(this.element.style.width=`${e}px`,this.element.style.height=`${t}px`)}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Te(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);kt==null||kt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){E.on(_.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&ne(this.track)}unbindEvents(){this.element&&ne(this.element),this.unbindTrackEvents(),E.off(_.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var s;switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(Z.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE);let o=this.container&&document.getElementById(this.container.id);o||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`);let n=at();this._pausedRetryCount>0&&(this.kind===h.VIDEO&&!sa()||this.kind===h.AUDIO&&(Q(n)&&n<=70||!o))&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),Je&&(this._interval=Z.run(Zi,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){let{code:a,message:c}=this.element.error;this._log.error(`${this.kind} player error observed. code: ${a} message: ${c} userAgent: ${navigator.userAgent}`),q.uploadEvent({log:`stat-${this.kind}-${be.PLAYER_ERROR}-${a}-${navigator.userAgent}`,error:this.element.error})}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(pt.LOADED_DATA);break}}handleTrackEvent(e){switch(e.type){case h.ENDED:this._log.info(`${this.kind} track is ended`),this.handleStopped(h.ENDED);break;case h.MUTE:this._log.info(`${this.kind} track is unable to provide media output`),this.handlePaused(h.MUTE);break;case h.UNMUTE:this._log.info(`${this.kind} track is able to provide media output`),this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(pt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(pt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(pt.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([ee([],"PLAYING")],Mt.prototype,"handlePlaying",1),y([ee("PLAYING","PAUSED",{ignoreError:!0})],Mt.prototype,"handlePaused",1),y([ee([],"STOPPED")],Mt.prototype,"handleStopped",1);var as=class extends Mt{constructor(e){super(e,h.VIDEO);d(this,"mirror");d(this,"objectFit");T(e.mirror)||(this.mirror=e.mirror),T(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var s;let e=document.createElement(h.VIDEO);if(this.track){let o=new MediaStream;o.addTrack(this.track),e.srcObject=o}e.muted=!0;let t=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;this.mirror&&(t+="transform: scaleX(-1);"),e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",t),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),(s=this.container)==null||s.appendChild(e),this.element=e,this.bindElementEvents()}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.mirror&&this.element){let s=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}setMirror(e){this.element&&(this.element.style.transform=e?"scaleX(-1)":""),this.mirror=e}setObjectFit(e){this.element&&(this.element.style.objectFit=`${e}`),this.objectFit=e}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){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}};var Dh='class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);',Rd=!1,oa=class{constructor(i){d(this,"context_");d(this,"blob_");this.context_=i.context,this.blob_=new Blob([Dh],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return p(this,null,function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),A.info("worklet addModule success"),E.emit(_.WORKLET_LOADED_SUCCESS),Rd=!0}catch(i){A.info(`worklet addModule catch error. ${i.message}`),E.emit(_.WORKLET_LOADED_FAILED)}})}get initWorkletSuccess(){return Rd}},Cd=oa;typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var vh=0,_t=(r,i)=>{let e=new window.AudioContext(i),t=++vh,s=()=>{e.state==="suspended"?(e.resume(),document.addEventListener("click",s)):e.state==="interrupted"?e.resume():document.removeEventListener("click",s)};return document.addEventListener("click",s),e.onstatechange=()=>{A.info(`${r}-${t} context state: ${e.state}`),s()},e};var it,To,go=0,na=class{constructor(i){d(this,"_volume");d(this,"_log");d(this,"_track");d(this,"_stream");d(this,"_audioCtx");d(this,"_destination");d(this,"_streamSource");d(this,"_scriptProcessorNode");d(this,"_audioWorkletNode");d(this,"_interval");let{track:e,log:t}=i;this._volume=0,this._log=t,this._track=e,it||(it=_t("volume-meter")),this._audioCtx=it,this._destination=this._audioCtx.destination;let s=new MediaStream;s.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(s),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,E.on(_.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),$n?(E.on(_.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),E.on(_.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),go+=1}preload(){To?To.initWorkletSuccess&&this.initAudioWorklet():To=new Cd({context:it})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=i=>{this._volume=i.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(i){q.logFailedEvent({userId:this._log.userId,eventType:be.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,E.off(_.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),E.off(_.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),E.off(_.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),go>0&&(go-=1),go===0&&(it==null||it.close(),it=null,To=null)}resume(){it==null||it.resume()}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Nd=na;var ei=null,aa=0,Ci=class extends Mt{constructor(e){super(e,h.AUDIO);d(this,"_volumeMeter");d(this,"_gainedTrack",null);d(this,"_gainNode",null);d(this,"_destination",null);d(this,"_mediaStreamSource",null);d(this,"_sourceElement",null);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_loop",!1);e.gainedTrack&&(this._gainedTrack=e.gainedTrack),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),e!==null&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new Nd({track:this._gainedTrack||e,log:this._log})}initializeElement(){if((Wt==="15.2"||Wt==="15.3"||Wt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=document.createElement(h.AUDIO);this.track&&(t.srcObject=new MediaStream([this._gainedTrack||this.track])),t.muted=this.muted,t.setAttribute("id",`audio_${this.id}`),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,this.bindElementEvents()}play(){return p(this,null,function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield At(Ci.prototype,this,"play").call(this)})}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),this.destroyGain(),super.stop()}resume(){return p(this,null,function*(){yield At(Ci.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()})}setSinkId(e){return p(this,null,function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)})}setVolume(e){this._volume=e,this._gainNode?this._gainNode.gain.value=e:e>1?this.createGain(e):this.element&&(this.element.volume=e)}createGain(e){ei||(ei=_t("player")),this._log.info(`create gainNode ${e}`);let t=ei.createMediaStreamSource(new MediaStream([this.track])),s=ei.createGain(),o=ei.createMediaStreamDestination();t.connect(s),s.connect(o),s.gain.value=e,this._gainNode=s,this._destination=o,this._mediaStreamSource=t,this._gainedTrack=o.stream.getAudioTracks()[0],aa+=1,this.element&&(ne(this.element),this._sourceElement=this.element,this.element.muted=!0,this.element=null),this.play()}destroyGain(){var e,t,s;!this._gainNode||(this._log.info("destroy gainNode"),(e=this._gainNode)==null||e.disconnect(),(t=this._destination)==null||t.disconnect(),(s=this._mediaStreamSource)==null||s.disconnect(),this._gainNode=null,this._destination=null,this._mediaStreamSource=null,this._sourceElement&&(this._sourceElement.srcObject=null,this._sourceElement=null),this._gainedTrack=null,aa-=1,aa===0&&ei&&(this._log.info("destroy gain audioContext"),ei.close(),ei=null))}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return((e=this._volumeMeter)==null?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return(e=this._volumeMeter)==null?void 0:e.getInternalAudioLevel()}};var Ni=class extends L{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,isInitPlayer:n=!0}){var a;super();d(this,"id",Wn());d(this,"userId");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"playerMuted",!1);d(this,"abortCtrl");d(this,"audioOutputDeviceId");d(this,"audioVolume");d(this,"objectFit","cover");d(this,"mirror",!1);d(this,"gain");d(this,"isScreen",!1);d(this,"manager");T(e)||(this.userId=e),this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Oe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Oe}),n&&this.initPlayer()}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get muted(){return!!(this.outMediaTrack&&!this.outMediaTrack.enabled)}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}play(e,t){return p(this,null,function*(){let s=de(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.isScreen?this.mirror=!1:t&&!T(t.mirror)&&(this.mirror=t.mirror),this.kind===h.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),de(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:t&&!T(t.mirror)&&(this.mirror=t.mirror),this.kind===h.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,s&&(this.container=s,this.player.setContainer(s)),E.emit(_.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this._outputTrack),yield this.player.play(),de(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),o.setContainer(null),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.mirror)||a.setMirror(t.mirror),T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new as({id:this.userId||this.id,track:this.outMediaTrack,container:n,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let o of s)yield o.play()})}initPlayer(){var e;this.log.info(`create ${this.kind}Player`),this.kind===h.AUDIO?this.player=new Ci({id:this.userId||this.id,track:this.outMediaTrack,gainedTrack:(e=this.gain)==null?void 0:e.audioTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new as({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(pt.LOADED_DATA,()=>{E.emit(_.VIDEO_LOADED_DATA,{track:this})}),this.player.on(pt.MEDIA_TRACK_CHANGED,t=>{var s;(s=this.subVideoPlayerMap)==null||s.forEach(o=>o.setTrack(t))})),this.player.on(pt.PLAYER_STATE_CHANGED,t=>{E.emit(_.PLAYER_STATE_CHANGED,N({track:this},t)),this.emit("player-state-changed",t)})}setAudioOutput(e){return p(this,null,function*(){var t;this.audioOutputDeviceId=e,yield(t=this.player)==null?void 0:t.setSinkId(e)})}setAudioVolume(e){var t;this.audioVolume=e,this.log.info(`setAudioVolume to ${e}`),(t=this.player)==null||t.setVolume(e)}getAudioLevel(){var e;return((e=this.player)==null?void 0:e.getAudioLevel())||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(),this.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop(),e.setContainer(null)}),this.container=null)}resume(){return p(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()}setMute(e){return this.outMediaTrack?(this.outMediaTrack.enabled=!e,this.emit(e?"mute":"unmute",this),E.emit(e?_.TRACK_MUTED:_.TRACK_UNMUTED,{track:this}),!0):!1}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}setInputMediaStreamTrack(e){let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this,t):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",((s=e.getSettings)==null?void 0:s.call(e).deviceId)||e.label),this._outputTrack=e,e.enabled=!this.muted,this.updatePlayingState(!!e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.outMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Id;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)})};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};y([ee([],L.INIT)],Ni.prototype,"close",1);var kh=Object.prototype.hasOwnProperty,{toString:xf}=Object.prototype;function Mh(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Fe(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(kh.call(r,i))return!1;return!0}}return!1}var Pt=Mh;var bd=Ne(Me(),1);var yd=r=>i=>i.deviceId===r;var ds=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(yd(s.deviceId))){let o=`${this.kind}${this.type}Added`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(yd(s.deviceId))){let o=`${this.kind}${this.type}Removed`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},ca=class extends bd.EventEmitter{constructor(){super();d(this,"audioInputs",new ds(h.AUDIO));d(this,"videoInputs",new ds(h.VIDEO));d(this,"audioOutputs",new ds(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this)),"ondevicechange"in navigator.mediaDevices||Z.run(gi,()=>{this.update()},{delay:1e4}))}init(){So().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,null,function*(){let e=yield So();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this})}},ae=$r||Ji?null:new ca;function So(){return p(this,null,function*(){return Xt()||!mo()?[]:(yield navigator.mediaDevices.enumerateDevices()).map((i,e)=>{let t={kind:i.kind,deviceId:i.deviceId,groupId:i.groupId,label:i.label||`${i.kind}_${e}`};return i.deviceId.length>0&&da.add(`${i.deviceId}_${i.kind}`),i.getCapabilities&&(t.getCapabilities=()=>i.getCapabilities()),t})})}function Pe(){return ae.update().then(r=>r.audioInputs.devices)}function Ge(){return ae.update().then(r=>r.videoInputs.devices)}function nr(){return p(this,null,function*(){return ae.update().then(r=>r.audioOutputs.devices)})}var da=new Set;function Od(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!da.has(t)}function Dd(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!da.has(t)}function ua(r,i){return p(this,null,function*(){let t=(yield Pe()).find(s=>s.deviceId===Ti);return(t==null?void 0:t.groupId)===r&&t.label===i})}function vd(o){return p(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Ti?yield ua(e,t):!0})}var Lh=function(r){return p(this,null,function*(){let i=xh(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Pe(),A.info(`microphones: ${ze(e,{keysToInclude:s})}`)),i.video&&(t=yield Ge(),A.info(`cameras: ${ze(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Yn&&o.getTracks().forEach(n=>{A.info(`${n.kind} capabilities: ${ze(n.getCapabilities(),{keysToInclude:no})}`)}),o}catch(o){if(o.name==="NotFoundError"){if(r.video&&t&&t.length===0)throw new C({code:g.DEVICE_NOT_FOUND,message:D({key:O.CAMERA_NOT_FOUND})});if(r.audio&&e&&e.length===0)throw new C({code:g.DEVICE_NOT_FOUND,message:D({key:O.MICROPHONE_NOT_FOUND})})}throw new C({code:g.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint})}})},Ph=ht({retryFunction:Lh,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retryCount:s})=>{r.name==="NotReadableError"?(t[0].video&&(t[0].maxResolution=!1,t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),s===2&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&kd(t[0].microphoneId,!1),t[0].cameraId&&kd(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{q.logFailedEvent({eventType:be.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{q.logSuccessEvent({eventType:be.GET_USER_MEDIA_RETRY}),q.uploadEvent({log:`stat-${be.GET_USER_MEDIA_RETRY}-success-${r}`})}});function kd(r,i){return p(this,null,function*(){let t=(i?yield Ge():yield Pe()).find(s=>s.deviceId===r);t&&j(t.getCapabilities)&&A.warn(ze(t.getCapabilities(),{keysToInclude:no}))})}function xh(r){return{audio:wh(r),video:Vh(r)}}function wh(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};return Pt(r.microphoneId)||(i.deviceId=r.useExact?{exact:r.microphoneId}:r.microphoneId),Q(r.channelCount)&&r.channelCount>1&&(i.channelCount=r.channelCount),re(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),re(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),re(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Pt(i)?!0:i}function Vh(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExact?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.width&&(e.width={ideal:r.width},i&&!X&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!X&&(e.height.max=r.height)),X&&je&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Pt(e)?!0:e}var Md=Ph;function Io(r){return G((i,e)=>function(...t){return p(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function Ao(r){return G((i,e)=>function(...t){return p(this,null,function*(){return r.call(this,i.apply(this,t))})})}function G(r){return function(i,e,t){return t.value=r(t.value,e),t}}var Oe=class extends Ni{constructor(e,t=!0){super({mediaType:e,isInitPlayer:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"profile");this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){Te(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ne(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){try{E.emit(_.LOCAL_TRACK_CAPTURE_START,{track:this});let t;e.customSource?(t=new MediaStream,t.addTrack(e.customSource)):t=yield Md(e);let s=t.getTracks()[0];return yield this.setInputMediaStreamTrack(s),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(_.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),t}catch(t){throw E.emit(_.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:t}),this.log.error(`getUserMedia error observed ${t}`),t}})}setInputMediaStreamTrack(e){this.state===L.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}publish(e,t){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),E.emit(_.LOCAL_TRACK_PUBLISHED,{track:this}),t}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(_.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&tt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield vd({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),So().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!Dd(this.mediaTrack)||this.kind===h.VIDEO&&!Od(this.mediaTrack)||this._isRecapturing||e&&je&&$e)}onTrackMuted(){if(!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<zi){setTimeout(()=>this.onTrackMuted(),zi);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;((e=this.mediaTrack)==null?void 0:e.muted)&&document.visibilityState==="visible"&&this.recapture(yield this.getRecoverCaptureDeviceId())}),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<zi){setTimeout(()=>this.onTrackEnded(),zi);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;let t;return this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(this.kind==="audio"?yield Pe():yield Ge()).find(n=>n.deviceId===e)&&(t=e),this.capture({deviceId:t,useExact:!0}).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})}).catch(n=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${n.message}`),this.emit("5",n)})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let{deviceId:e}=this;if(e){let t=(us.get(e)||0)+1;if(us.set(e,t),t>=3){let s=this.kind==="video"?(yield Ge()).find(o=>!us.has(o.deviceId)):(yield Pe()).find(o=>!us.has(o.deviceId));s&&(this.log.warn(`${e} capture fail ${t} times, change new ${s.deviceId}`),e=s.deviceId)}}return e})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};y([ee(L.INIT,"capture",{ignoreError:!0})],Oe.prototype,"setStateToCapture",1),y([ee("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===g.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Oe.prototype,"publish",1),y([G(r=>function(){return p(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),this.mediaType===2&&(this.mediaType=4)})}),ee([],"capture")],Oe.prototype,"unpublish",1);var us=new Map;E.on(_.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&us.delete(r.track.deviceId)});var ve=class extends Oe{constructor(e){super(1);d(this,"mediaType",1);d(this,"volume",0);d(this,"captureVolume",1);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);this.manager=e}getAudioLevel(){return this.volume||super.getAudioLevel()}capture({deviceId:e,customSource:t,useExact:s=!1}={}){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,useExact:s,customSource:t})}switchDevice(e){return p(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Ti){if(yield ua(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,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),E.emit(_.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ae&&!ae.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ae.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`);let t=yield Pe();t[0]?this.recapture(t[0].deviceId):ae.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!T(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}setCaptureVolume(e){var s;let t=e/100;t!==this.captureVolume&&((s=this.manager)==null||s.setCaptureVolume(t),this.captureVolume=t)}close(){ae.off("audioInputAdded",this.handleMicrophoneAdded,this),ae.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};var ke=class extends Oe{constructor(e){super(4);d(this,"mediaType",4);d(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});d(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});d(this,"small");d(this,"facingMode");d(this,"isNeedToSetBandwidth");this.manager=e;let t=()=>{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(M(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t)}capture({deviceId:e,facingMode:t,useExact:s=!1,customSource:o}={}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:s,customSource:o})}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}setProfile(e){!e||(e.bitrate&&(this.isNeedToSetBandwidth=e.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(e):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(M(N({},this.profile),{width:1920,height:1080}))))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(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:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return tt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){let t=e;try{if(!this.isNeedToSwitchDevice(t))return;(t===h.FACING_MODE_USER||t===h.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,t=void 0),this.mediaTrack.stop(),yield this.capture({deviceId:t,useExact:!0}),E.emit(_.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(s){throw this.log.error(`switch camera failed ${s}`),this.deviceId&&this.recapture(this.deviceId),s}})}listenDeviceChange(){ae&&!ae.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&ae.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`);let t=yield Ge();t[0]?this.recapture(t[0].deviceId):ae.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){ae.off("videoInputAdded",this.handleCameraAdded,this),ae.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}};var $h=function(r){return p(this,null,function*(){let i=null,e=Hh(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);if(r.systemAudio&&t.getAudioTracks().length===0&&(Wi&&mi<74||$e||X)&&A.warn("Your browser not support capture system audio"),r.frameRate&&t.getVideoTracks()[0]&&t.getVideoTracks()[0].applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height}).catch(s=>{A.warn(`screen applyConstraints failed: ${s}`)}),r.audio){let s=Fh(r);A.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function Fh(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return T(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function Hh(r){let i={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:$e?{max:r.width}:{ideal:r.width,max:r.width},height:$e?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var xd=$h;var xe=class extends ke{constructor(e){super(e);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a}={}){try{let c;return a||n?(c=new MediaStream,a&&c.addTrack(a),n&&c.addTrack(n)):c=yield xd({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o}),yield this.setInputMediaStreamTrack(c.getVideoTracks()[0]),c}catch(c){throw this.log.error(`getDisplayMedia error observed ${c}`),c instanceof C?c:new C({code:g.INITIALIZE_FAILED,name:c.name,message:c.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};var xt=class extends ve{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var ar=class extends ve{constructor(e){super(e);d(this,"_inputs",new Map);d(this,"_destination");d(this,"audioContext",_t("audio-mixer"));this._log.id=`m-${this._log.id}`,this.audioContext.state!=="running"&&this._log.warn(`audio mixer context state: ${this.audioContext.state}`),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1}setInputMediaStreamTrack(e){this._inputTrack=e;let t=this.audioContext.createMediaStreamSource(new MediaStream([e]));this._inputs.set(e,{sourceNode:t}),t.connect(this._destination),this._outputTrack||(this._outputTrack=this._destination.stream.getAudioTracks()[0],this.setStateToCapture())}setTrackCaptureVolume(e,t){if(!this._inputs.has(e)||!this._destination)return;let s=this._inputs.get(e),{sourceNode:o}=s;s.gainNode||(this._log.info("create GainNode"),s.gainNode=this.audioContext.createGain()),s.gainNode.gain.value=t,o.disconnect(),o.connect(s.gainNode).connect(this._destination)}publish(e,t){return this.room=e,t}unpublish(){delete this.room}replaceTrack(e,t){var s;!this.hasMix||(t&&((s=this._inputs.get(t))==null||s.sourceNode.disconnect(),this._inputs.delete(t)),this.setInputMediaStreamTrack(e.outMediaTrack))}removeTrack(e){var t;(t=this._inputs.get(e))==null||t.sourceNode.disconnect(),this._inputs.delete(e),this._inputs.size===0&&(delete this._outputTrack,this.unpublish())}close(){this.stop(),this.audioContext.close()}get hasMix(){return!!this._outputTrack}set channelCount(e){this._destination.channelCount=e}};y([ee("capture","publish",{ignoreError:!0})],ar.prototype,"publish",1),y([ee([],"capture")],ar.prototype,"unpublish",1);var ti=class extends Oe{constructor(e,t){super(1);d(this,"musicId");d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!1);d(this,"audio");d(this,"_audioContext");d(this,"_destination");d(this,"_source",null);this.manager=e,this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.audio=document.createElement("audio"),this.audio.src=t.url,this.audio.crossOrigin="anonymous",re(t.loop)&&this.loop(t.loop),Q(t.volume)&&this.setVolume(t.volume),t.id&&(this.musicId=t.id),this._source=this._audioContext.createMediaElementSource(this.audio),this._source.connect(this._destination),this.setInputMediaStreamTrack(this._destination.stream.getAudioTracks()[0]),this.installPlayerEvent()}play(){return p(this,null,function*(){try{yield this.audio.play(),yield At(ti.prototype,this,"play").call(this,null,{muted:!1}),this._log.info(`music ${this.musicId} play success`)}catch(e){this._log.error(`music ${this.musicId} play error`,e)}})}installPlayerEvent(){this.audio.addEventListener("error",this.handleAudioError.bind(this))}uninstallPlayerEvent(){this.audio.removeEventListener("error",this.handleAudioError.bind(this))}handleAudioError(e){this._log.warn(`local music ${this.musicId} audio error`,e)}initAudioContext(){this._audioContext=_t("music"),this._audioContext.state!=="running"&&this._log.warn(`local music ${this.musicId} context state: ${this._audioContext.state}`)}destroy(){var e,t;(e=this._source)==null||e.disconnect(),(t=this._destination)==null||t.disconnect(),this.uninstallPlayerEvent(),this.player.stop(),this._audioContext.close().then(()=>{this._source=null,this._destination=null,this._audioContext=null})}getStream(){var e;return((e=this._destination)==null?void 0:e.stream)||null}seek(e){if(e<0&&e>this.duration()){this._log.warn("Time beyond song duration.");return}this.audio.currentTime=e}getPosition(){return this.audio.currentTime||0}setVolume(e){if(e>1&&e<0){this.log.warn("volume is out of range");return}this.audio.volume=e}getVolume(){return this.audio.volume||0}setPlayBackRate(e){if(e>8&&e<0){this.log.warn("rate is out of range");return}this.audio.playbackRate=e}getPlayBackRate(){return this.audio.playbackRate||0}duration(){return this.audio.duration||0}loop(e){return this.audio&&re(e)&&(this.audio.loop=e),this.audio.loop||!1}setOperation(e){e==="pause"&&this.audio.pause(),e==="resume"&&(this.audio.pause(),this.audio.play()),e==="stop"&&(this.audio.pause(),this.seek(0))}listenDeviceChange(){}};var ii="input",yi="output",wd="ondump",Vd="dumped";function Gh(r){let i;return Wh(r)?i="intl-schedule.rtc.qq.com":i="schedule.rtc.qq.com",i}var Wh=r=>(r=Number(r),r>0&&r<14e8);function Ud(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${Gh(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:u,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:u};let f="Init RTCAIDenoiser failed.",I="";switch(c){case 1:I="Please check your params.";break;case 2:I="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:I="Server is invalid. Please contact our engineer. ";break;case 4:I="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:I="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:I="Your version is not supported.";break}return{auth:!1,status:m,message:u?`${f} Reason: ${u}. ${I}`:`${f}, ${I}`}})}var $d=Ne(Me(),1);function Bd(r,i){i=i||{};let e=r.numberOfChannels,{sampleRate:t}=r,s=i.float32?3:1,o=s===3?32:16,n;return e===2?n=Jh(r.getChannelData(0),r.getChannelData(1)):n=r.getChannelData(0),Kh(n,s,t,e,o)}function Kh(r,i,e,t,s){let o=s/8,n=t*o,a=new ArrayBuffer(44+r.length*o),c=new DataView(a);return Ro(c,0,"RIFF"),c.setUint32(4,36+r.length*o,!0),Ro(c,8,"WAVE"),Ro(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,i,!0),c.setUint16(22,t,!0),c.setUint32(24,e,!0),c.setUint32(28,e*n,!0),c.setUint16(32,n,!0),c.setUint16(34,s,!0),Ro(c,36,"data"),c.setUint32(40,r.length*o,!0),i===1?Yh(c,44,r):jh(c,44,r),a}function Jh(r,i){let e=r.length+i.length,t=new Float32Array(e),s=0,o=0;for(;s<e;)t[s++]=r[o],t[s++]=i[o],o++;return t}function jh(r,i,e){for(let t=0;t<e.length;t++,i+=4)r.setFloat32(i,e[t],!0)}function Yh(r,i,e){for(let t=0;t<e.length;t++,i+=2){let s=Math.max(-1,Math.min(1,e[t]));r.setInt16(i,s<0?s*32768:s*32767,!0)}}function Ro(r,i,e){for(let t=0;t<e.length;t++)r.setUint8(i+t,e.charCodeAt(t))}var la=class{constructor(i){d(this,"audioContext_");d(this,"inputPCM_",new Float32Array);d(this,"outputPCM_",new Float32Array);this.audioContext_=i}onDump(i,e){if(e===ii){let t=this.inputPCM_.length,s=new Float32Array(t+i[0].length);s.set(this.inputPCM_),s.set(i[0],t),this.inputPCM_=s}if(e===yi){let t=this.outputPCM_.length,s=new Float32Array(t+i[0].length);s.set(this.outputPCM_),s.set(i[0],t),this.outputPCM_=s}}getBlob(i){let e=i===ii?this.inputPCM_:this.outputPCM_,t=this.audioContext_.createBuffer(2,e.length,48e3);t.copyToChannel(e,0,0),t.copyToChannel(e,1,0);let s=Bd(t),o=new window.Blob([new DataView(s)],{type:"audio/wav"});return t=null,o}reset(){this.inputPCM_=new Float32Array,this.outputPCM_=new Float32Array}destroy(){this.reset()}},ha=la;var ma=class{constructor({sdkAppId:i,userId:e,audioContext:t,sign:s,status:o,worklet:n,timestamp:a,logger:c}){d(this,"audioContext_");d(this,"destination_");d(this,"gainNode_");d(this,"log_");d(this,"workletNode_");d(this,"isDumping_",!1);d(this,"dump_");d(this,"trackConstraint_",{});d(this,"audioTrack_");d(this,"source_");d(this,"denoiserTrack_");d(this,"enableDenoise_",!0);d(this,"emitter_",new $d.default);this.audioContext_=t,this.destination_=this.audioContext_.createMediaStreamDestination(),this.gainNode_=this.audioContext_.createGain(),this.gainNode_.gain.value=1.1,this.log_=c,this.workletNode_=n,this.workletNode_.connect(this.gainNode_).connect(this.destination_),this.workletNode_.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:e,timestamp:a,sign:s,status:o}}),this.workletNode_.port.onmessage=u=>{let{type:l,data:m}=u.data;if(l===wd&&this.isDumping_){let{inputPCM:f,outputPCM:I}=m;this.dump_.onDump(f,ii),this.dump_.onDump(I,yi)}l===Vd&&this.dumped()},this.dump_=new ha(this.audioContext_)}dumped(){this.isDumping_=!1;let i=this.dump_.getBlob(ii),e=this.dump_.getBlob(yi);this.emitter_.emit("ondumpend",{blob:i,name:ii}),this.emitter_.emit("ondumpend",{blob:e,name:yi}),this.dumpedWAV(i,ii),this.dumpedWAV(e,yi),this.dump_.reset()}dumpedWAV(i,e){let t=window.URL.createObjectURL(i),s=document.createElement("a");s.href=t,s.download=`${e}-${Date.now()}.wav`,s.click(),window.URL.revokeObjectURL(t),s.href=""}process(i){return p(this,null,function*(){if(this.audioTrack_=i,!this.audioTrack_)throw new Error("RTCAIDenoiser: cannot process without audioTrack.");let e=new MediaStream;e.addTrack(this.audioTrack_),this.source_=this.audioContext_.createMediaStreamSource(e),yield this.source_.connect(this.workletNode_),this.trackConstraint_=this.audioTrack_.getConstraints(),this.trackConstraint_.noiseSuppression=!1,yield this.audioTrack_.applyConstraints(this.trackConstraint_);let t=this.destination_.stream;return this.denoiserTrack_=t.getAudioTracks()[0],this.log_.info(`RTCAIDenoiser: denoiser process track ID: ${i.id} success.`),this.denoiserTrack_})}updateTrack(i){return p(this,null,function*(){var s;let e=new MediaStream;yield e.addTrack(i);let t=this.audioContext_.createMediaStreamSource(e);this.source_.disconnect(),t.connect(this.workletNode_),(s=this.audioTrack_)==null||s.stop(),this.audioTrack_=i,this.source_=t,this.log_.info("RTCAIDenoiser: updateTrack success.")})}disable(){return p(this,null,function*(){var i,e;return this.enableDenoise_=!1,(i=this.workletNode_)==null||i.port.postMessage({type:"disable"}),this.trackConstraint_.noiseSuppression=!0,yield(e=this.audioTrack_)==null?void 0:e.applyConstraints(this.trackConstraint_),this.log_.info("RTCAIDenoiser: disable ai denoiser."),this.enableDenoise_})}enable(){return p(this,null,function*(){var i,e;return this.enableDenoise_=!0,(i=this.workletNode_)==null||i.port.postMessage({type:"enable"}),this.trackConstraint_.noiseSuppression=!1,yield(e=this.audioTrack_)==null?void 0:e.applyConstraints(this.trackConstraint_),this.log_.info("RTCAIDenoiser: enable ai denoiser."),this.enableDenoise_})}startDump(){return this.isDumping_?(this.log_.info("RTCAIDenoiser: data is currently being dumped."),!1):(this.workletNode_.port.postMessage({type:"startDump"}),this.dump_?this.dump_.reset():this.dump_=new ha(this.audioContext_),this.isDumping_=!0,this.log_.info("RTCAIDenoiser: start dump data."),!0)}stopDump(){!this.isDumping_||(this.workletNode_.port.postMessage({type:"stopDump"}),this.isDumping_=!1,this.log_.info("RTCAIDenoiser: stop dump data."))}getAudioTrack(){return this.audioTrack_}getDenoiserTrack(){return this.destination_.stream.getAudioTracks()[0]}get enabled(){return this.enableDenoise_}destroy(){var i,e,t,s,o,n;this.log_.info("RTCAIDenoiser: destroy processor."),(i=this.audioTrack_)==null||i.stop(),(e=this.workletNode_)==null||e.port.postMessage({type:"destroy"}),this.workletNode_.port.onmessage=null,(t=this.source_)==null||t.disconnect(),(s=this.destination_)==null||s.disconnect(),(o=this.workletNode_)==null||o.disconnect(),(n=this.dump_)==null||n.destroy(),this.emitter_.removeAllListeners()}on(i,e,t){this.emitter_.on(i,e,t)}off(i,e,t){i==="*"?this.emitter_.removeAllListeners():this.emitter_.off(i,e,t)}},Fd=ma;var pa=class{constructor({assetsPath:i,log:e,audioContext:t}){this.isLoaded_=!1;this.audioContext_=t,this.log_=e,this.assetsPath_=i}createProcessor(i){return p(this,null,function*(){let e=String(Date.now()).slice(0,-3),{auth:t,sign:s,status:o,message:n}=yield Ud(M(N({},i),{timestamp:e}));if(!t)throw this.log_.info(`RTCAIDenoiser: ${i.userId} auth result: ${t}. Message: ${n}`),new Error(n);try{yield this.load()}catch(u){throw new Error("Init wasm failed, please check your assetsPath.")}let a=yield this.initWorklet(),c=new Fd(M(N({},i),{audioContext:this.audioContext_,timestamp:e,sign:s,status:o,worklet:a,logger:this.log_}));return this.log_.info(`RTCAIDenoiser: ${i.userId} create denoiser processor success.`),c})}load(){return p(this,null,function*(){if(!this.isLoaded_)try{yield this.audioContext_.audioWorklet.addModule(`${this.assetsPath_}/denoiser-wasm.js`),this.isLoaded_=!0}catch(i){throw this.log_.error(`Init assets from ${this.assetsPath_} failed! Reason: ${i}`),i}})}initWorklet(){return p(this,null,function*(){try{return new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}catch(i){return yield this.load(),new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}})}destroy(){var i;(i=this.audioContext_)==null||i.close()}isSupported(){return"AudioWorklet"in window&&"WebAssembly"in window}},Hd=pa;var Co=class{constructor({room:i}){d(this,"_localAudioTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"localMixAudioTrack");d(this,"isDenoiserInit",!1);d(this,"isDenoiserEnabled",!1);d(this,"isDenoiserProcessed",!1);d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);d(this,"_log");d(this,"denoiserTrack",null);d(this,"denoiser",null);d(this,"denoiserProcessor");d(this,"initProcessorOptions");d(this,"denoiserContext");this._log=A.createLogger({id:"am",userId:i.userId,sdkAppId:i.sdkAppId})}get mixedAudioTrack(){return this.localMixAudioTrack?this.localMixAudioTrack.outMediaTrack:null}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(i,e){var t,s,o;if(i instanceof xt){this._localScreenAudioTrack=i,i._outputTrack=i.mediaTrack;return}if(i instanceof ti){i._outputTrack=i.mediaTrack,(t=this.localMixAudioTrack)==null||t.replaceTrack(i,e);return}if(i instanceof ve){this._localAudioTrack=i,this.isDenoiserProcessed&&((s=this.denoiserProcessor)==null||s.updateTrack(i.mediaTrack)),i.setOutputMediaStreamTrack(this.isDenoiserProcessed?this.denoiserTrack:i.mediaTrack),(o=this.localMixAudioTrack)==null||o.replaceTrack(i,e);return}if(i instanceof wt)return i.setOutputMediaStreamTrack(i.mediaTrack)}removeInput(i){if(i instanceof ve)return this.removeAudioTrack(i);i instanceof wt}addMusicSource(i){return p(this,null,function*(){this._log.info(`add music source, id: ${i.id} url: ${i.url}`);let{id:e,url:t,loop:s,volume:o}=i;if(this.mixedMusicMap.has(e))return;let n;return this.cacheMusicMap.has(e)?n=this.cacheMusicMap.get(e):n=new ti(this,i),n.play(),this._log.info(`start mix audio ${e} success.`),this.mixedMusicMap.set(e,n),this.cacheMusicMap.set(e,n),n})}updateMusicSource(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:o,seekFrom:n}=i;if(this._log.info(`update music source, ${JSON.stringify(i)}`),this.mixedMusicMap.has(e)){let a=this.mixedMusicMap.get(e);T(t)||a.setVolume(t),T(s)||a.loop(s),T(o)||a.setOperation(o),T(n)||a.seek(n)}})}addAudioTrack(i){return p(this,null,function*(){var e;if(this.localMixAudioTrack||(this.localMixAudioTrack=new ar(this)),this._log.info(`start add audioTrack, userId: ${i.userId}`),i===this._localAudioTrack){if(tt){let t=yield(e=i.mediaTrack)==null?void 0:e.getSettings();this.localMixAudioTrack.channelCount=(t==null?void 0:t.channelCount)||1}this.mixedMusicMap.forEach(t=>{var s;(s=this.localMixAudioTrack)==null||s.setInputMediaStreamTrack(t.outMediaTrack)})}this.localMixAudioTrack.setInputMediaStreamTrack(i.outMediaTrack),this._localAudioTrack&&this._localAudioTrack.captureVolume!==1&&this.setCaptureVolume(this._localAudioTrack.captureVolume)})}removeAudioTrack(i){!this.localMixAudioTrack||(i===this._localAudioTrack&&this.mixedMusicMap.forEach(e=>{this.localMixAudioTrack.removeTrack(e.outMediaTrack)}),this.localMixAudioTrack.removeTrack(i.outMediaTrack))}removeMusicSource({id:i}){if(!!this.localMixAudioTrack){if(this.mixedMusicMap.has(i)){this._log.info(`remove music source, music id: ${i}`);let e=this.mixedMusicMap.get(i);e.stop(),this.localMixAudioTrack.removeTrack(e.outMediaTrack),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()}}destroyAllMusic(){this._log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{this.removeMusicSource({id:e})})}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach(i=>i.stop())}initDenoiser(i){return p(this,null,function*(){let{assetsPath:e,sdkAppId:t,userId:s,userSig:o}=i;try{(!this.denoiserContext||this.denoiserContext.state==="closed")&&(this.denoiserContext=_t("denoiser")),this.denoiser||(this.denoiser=new Hd({assetsPath:e,log:this._log,audioContext:this.denoiserContext})),this.denoiserProcessor||(this.denoiserProcessor=yield this.denoiser.createProcessor({sdkAppId:t,userId:s,userSig:o})),this.isDenoiserInit=!0,this.initProcessorOptions=i}catch(n){throw n}})}enableDenoiser(i){return p(this,null,function*(){var e,t,s;if(this.isDenoiserEnabled=!0,!this.hasAudioTrack){let o="enableDenoiser failed, there is no audio";throw this._log.error(o),new Error(o)}if(this.isDenoiserProcessed)(s=this.denoiserProcessor)==null||s.enable();else{let o=(e=this._localAudioTrack)==null?void 0:e.mediaTrack;if(!o)return;this.denoiserProcessor||(yield this.initDenoiser(this.initProcessorOptions)),this.denoiserTrack=yield this.denoiserProcessor.process(o),this.isDenoiserProcessed=!0,this._localAudioTrack._outputTrack=this.denoiserTrack,(t=this.localMixAudioTrack)==null||t.replaceTrack(this._localAudioTrack,o)}})}disableDenoiser(){return p(this,null,function*(){var i;this.isDenoiserEnabled&&((i=this.denoiserProcessor)==null||i.disable(),this.isDenoiserEnabled=!1)})}setCaptureVolume(i){var e;this.localMixAudioTrack&&this._localAudioTrack&&this._localAudioTrack.mediaTrack&&((e=this.localMixAudioTrack)==null||e.setTrackCaptureVolume(this._localAudioTrack.mediaTrack,i))}destroyDenoiserProcessor(){var i;this.denoiserProcessor&&(this.denoiserProcessor.destroy(),delete this.denoiserProcessor,this.isDenoiserInit=!1,this.isDenoiserEnabled=!1,this.isDenoiserProcessed=!1,(i=this.denoiserTrack)==null||i.stop(),this.denoiserTrack=null),this.denoiserContext&&(this.denoiserContext.close(),delete this.denoiserContext)}destroy(){var i;this.destroyAllMusic(),this.destroyAllCache(),this.destroyDenoiserProcessor(),(i=this.denoiser)==null||i.destroy(),this.localMixAudioTrack&&(this.localMixAudioTrack.close(),delete this.localMixAudioTrack)}};var _a=class extends Ni{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);this.tinyId=t.tinyId}setMute(e){return this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&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===_a.STATE_SUBSCRIBE}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed:${this.isSubscribed} hasFlag:${this.hasFlag} hasTrack:${!!this.outMediaTrack}`);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},rt=_a;d(rt,"STATE_SUBSCRIBE","subscribe"),y([ee(L.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),E.emit(_.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],rt.prototype,"subscribe",1),y([ee(rt.STATE_SUBSCRIBE,L.INIT,{success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),E.emit(_.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],rt.prototype,"unsubscribe",1);var wt=class extends rt{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}getAudioLevel(){return this.volume||super.getAudioLevel()}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var ft=class extends rt{constructor(e,t,s=4){super(e,t,s);d(this,"mediaType",4);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}},cr=class extends ft{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function he(...r){}var Qh=r=>r();function Ea(){this.dispose()}var qh=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Xh=1,Vt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new fa(i,this,this.streamId++);return st.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ls=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=he,this.error=he,this.next=he,this.dispose=he,this.subscribe=he,this.doDefer()}subscribe(i){return i instanceof Vt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Qh),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}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}},w=class extends ls{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}};function Gd(r,...i){return i.reduce((e,t)=>t(e),r)}function Ut(r,i,e){if(qh()){let t=Object.defineProperties(Object.setPrototypeOf(r,Vt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});st.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof Vt&&st.addSource(t,o)}return t}return r}function F(r,i){return function(...e){return t=>{if(t instanceof Vt){let s=Ut(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,st.pipe(s),s}else return s=>t(new r(s,...e))}}}function ri(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var fa=class extends w{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{st.defer(this.source,this.id)})}next(i){st.next(this.source,this.id,i),this.sink.next(i)}complete(){st.complete(this.source,this.id),this.sink.complete()}error(i){st.complete(this.source,this.id,i),this.sink.error(i)}},st={addSource(r,i){ri("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){ri("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){ri("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){ri("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){ri("defer",{id:r.id,streamId:i})},pipe(r){ri("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){ri("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=Xh++),ri("create",{name:r.toString(),id:r.id})}},No=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Ta=class extends ls{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function yo(){return r=>{let i=new Ta(r);if(r instanceof Vt){let e=Ut(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,st.pipe(e),e}return Ut(i.add.bind(i),"share",arguments)}}function zh(...r){return Ut(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(c,u)=>{let l=new w(i);l.next=m=>{--t===0?(l.next=f=>{o[u]=f,i.next(o)},l.next(m)):o[u]=m},l.complete=n,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var ga=class extends w{constructor(i,...e){super(i);let t=new w(this.sink);t.next=s=>this.buffer=s,t.complete=he,t.subscribe(zh(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},tg=F(ga,"withLatestFrom"),Sa=class extends w{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),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(i=>this.sink.next(i)),super.complete()}},ig=F(Sa,"bufferCount"),Ia=class extends w{constructor(i,e){super(i),this.buffer=[];let t=new w(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=he,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},rg=F(Ia,"buffer");function Aa(r){let i=arguments,e=yo()(Ut(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=he,e.complete=he,e.error=he,e}function Wd(r){return Ut(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var Ra=class extends w{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},Zh=F(Ra,"reduce");var Ca=class extends w{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},em=F(Ca,"filter"),Na=class extends w{next(i){}},pg=F(Na,"ignoreElements"),ya=class extends w{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},tm=F(ya,"take"),ba=class extends w{constructor(i,e){super(i);let t=new w(i);t.next=()=>i.complete(),t.complete=Ea,t.subscribe(e)}},_g=F(ba,"takeUntil"),Oa=class extends w{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},im=F(Oa,"takeWhile");var Da=class extends w{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},fg=F(Da,"skip"),va=class extends w{constructor(i,e){super(i),i.next=he;let t=new w(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Ea,t.subscribe(e)}},Eg=F(va,"skipUntil"),ka=class extends w{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},rm=F(ka,"skipWhile"),sm={leading:!0,trailing:!1},Ma=class extends w{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},La=class extends w{constructor(i,e,t=sm){super(i),this.durationSelector=e,this.config=t,this._throttle=new Ma(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=he,this._throttle.complete(),super.complete()}},Tg=F(La,"throttle");var Pa=class extends w{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},xa=class extends w{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Pa(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},gg=F(xa,"debounce");var wa=class extends w{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,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()}},Sg=F(wa,"elementAt");var Va=class extends w{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},Ig=F(Va,"findIndex"),Ua=class extends w{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,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()}},Ag=F(Ua,"first"),Ba=class extends w{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},Rg=F(Ba,"last"),$a=class extends w{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,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()}},Cg=F($a,"every");var Fa=class extends w{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},Og=F(Fa,"scan"),Ha=class extends w{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},Dg=F(Ha,"pairwise"),Ga=class extends w{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Kd=F(Ga,"map");var dr=class extends w{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ur=class extends w{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},bo=class extends dr{},Oo=class extends ur{next(i){this.subInner(i,bo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,bo)}}},om=F(Oo,"switchMap");function Mo(r){return(i,e)=>r(()=>i,e)}var vg=Mo(F(Oo,"switchMapTo")),Wa=class extends dr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Do=class extends ur{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),Wa),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},kg=F(Do,"concatMap"),Mg=Mo(F(Do,"concatMapTo")),Ka=class extends dr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},vo=class extends ur{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Ka),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},Lg=F(vo,"mergeMap"),Pg=Mo(F(vo,"mergeMapTo")),Ja=class extends dr{dispose(){this.context.resetNext(),super.dispose()}},ko=class extends ur{next(i){this.next=he,this.subInner(i,Ja)}},xg=F(ko,"exhaustMap"),wg=Mo(F(ko,"exhaustMapTo")),ja=class extends w{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=Aa(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},Vg=F(ja,"groupBy"),Ya=class extends w{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},Ug=F(Ya,"timeInterval"),Qa=class extends w{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},Bg=F(Qa,"bufferTime"),qa=class extends w{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},$g=F(qa,"delay"),Xa=class extends w{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Fg=F(Xa,"catchError");var za=class extends w{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Kg=F(za,"tap"),Za=class extends w{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new No(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Jg=F(Za,"timeout");var dS=Gd(Wd(250),Kd(()=>performance.now()),yo());var lr=new Map;E.on(_.JOIN_SUCCESS,({room:r})=>{pe(r.userId,{eventId:32788,eventDesc:"join room"})});E.on(_.LEAVE_START,({room:r})=>{pe(r.userId,{eventId:32789,eventDesc:"leave room"})});E.on(_.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),pe(r.room.userId,{eventId:i,eventDesc:`publish ${r.kind}`})}});E.on(_.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),pe(r.room.userId,{eventId:i,eventDesc:`unpublish ${r.kind}`})}});E.on(_.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?pe(r.room.userId,{eventId:r.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:r.isRemote?r.userId:void 0}):pe(r.room.userId,{eventId:r.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:r.isRemote?r.userId:void 0}))});E.on(_.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?pe(r.room.userId,{eventId:r.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:r.isRemote?r.userId:void 0}):pe(r.room.userId,{eventId:r.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:r.isRemote?r.userId:void 0}))});E.on(_.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&pe(r.room.userId,{eventId:32777,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&pe(r.room.userId,{eventId:32776,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&pe(r.room.userId,{eventId:32803,eventDesc:`${h.SUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});E.on(_.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&pe(r.room.userId,{eventId:32779,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&pe(r.room.userId,{eventId:32778,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&pe(r.room.userId,{eventId:32804,eventDesc:`${h.UNSUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});E.on(_.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&pe(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781,eventDesc:`switch ${r.kind===h.VIDEO?"camera":"microphone"}`})});E.on(_.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&pe(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783,eventDesc:`replace ${r.kind}`})});E.on(_.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e})=>{let t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?(t=32795,s="signal reconnected"):(t=32791,s="signal connected");break;case"DISCONNECTED":i==="RECONNECTING"?(t=32796,s="signal reconnect fail"):(t=32790,s="signal disconnected");break;case"RECONNECTING":t=32794,s="signal reconnecting";break}t&&s&&pe(r.userId,{eventId:t,eventDesc:s})});E.on(_.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,o=s?"downlink":"uplink",n,a;switch(e){case"CONNECTED":i==="RECONNECTING"?(n=s?32801:32798,a=`${o} reconnected`):(n=s?32793:32792,a=`${o} connected`);break;case"DISCONNECTED":i==="RECONNECTING"&&(n=s?32802:32799,a=`${o} reconnect fail`);break;case"RECONNECTING":n=s?32800:32797,a=`${o} reconnecting`;break}n&&a&&pe(r.userId,{eventId:n,eventDesc:a,remoteUserId:t})});function pe(r,i){let e=M(N({},i),{timestamp:Cr()});lr.has(r)?lr.get(r).push(e):lr.set(r,[e])}function Jd(r){if(lr.has(r)){let i=lr.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return lr.delete(r),i}return[]}var jd=Ne(Me(),1);var Lo=class extends jd.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Un[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let s=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=Qt(o,n),u=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(u){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==o&&(m.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:u,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Qt(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Yd({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return G((t,s)=>{let o=new Map;return E.on(_.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new C({code:g.INVALID_OPERATION,message:D({key:O.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var Qd=!0,qd=function(){var r;Qd&&(Qd=!1,A.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ct}/en/index.html`),console.info(`* Changelog: ${ct}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),A.info("TRTC Web SDK Version:",Ie),A.info("UA:",navigator.userAgent),A.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),Br().then(i=>{if(i){let e=`UAData: ${i.platform}/${i.platformVersion}`;i.architecture&&i.bitness&&(e+=` ${i.architecture}/${i.bitness}`),i.mobile&&(e+=" mobile"),i.model&&(e+=` model: ${i.model}`),i.fullVersionList&&(e+=` ${i.fullVersionList.filter(t=>t.brand!=="Not/A)Brand").map(t=>`${t.brand}/${t.version}`).join(",")}`),A.info(e)}}))};var hs={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"};var U={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},si=(S=>(S[S.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",S[S.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",S[S.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",S[S.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",S[S.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",S[S.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",S[S.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",S[S.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",S[S.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",S[S.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",S[S.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",S[S.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",S[S.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",S[S.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",S[S.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",S[S.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",S[S.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",S[S.INVALID_OPERATION=5100]="INVALID_OPERATION",S[S.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",S[S.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",S[S.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",S[S.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",S[S.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",S[S.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",S[S.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",S[S.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",S[S.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",S[S.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",S[S.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",S[S.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",S[S.DEVICE_ERROR=5300]="DEVICE_ERROR",S[S.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",S[S.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",S[S.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",S[S.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",S[S.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",S[S.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",S[S.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",S[S.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",S[S.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",S[S.SERVER_ERROR=5400]="SERVER_ERROR",S[S.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",S[S.OPERATION_FAILED=5500]="OPERATION_FAILED",S[S.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",S[S.REJOIN_FAILED=5502]="REJOIN_FAILED",S[S.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",S[S.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",S[S.OPERATION_ABORT=5998]="OPERATION_ABORT",S[S.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",S))(si||{});function zd({code:r,params:i,enableDocLink:e=!1}){let t="",s,o=si[r];try{s=Xd[o]}catch(n){s=Xd.UNKNOWN_ERROR}return j(s)?t=s(i):Y(s)&&(t=s),e&&(t+=" doc:"),t}var Xd=M(N({},me),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${oe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${oe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' 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:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,MIX_PARAMS_USER_Z_ORDER({key:r}){return`'${r}' is required and must be between 1 and 15.`},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_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_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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.",DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=bi(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=bi(r),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:i=bi(r),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:i=bi(r),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:r,deviceType:i=bi(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:i=bi(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:i=bi(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function bi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var hr=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:o,fnName:n="",originError:a}){var u;let c;s?c=s:c=zd({code:t||e,params:N({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=si[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((u=this.originError)==null?void 0:u.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},f=document.createElement("a");Rt?f.href=`ms-settings:privacy-${m[this.functionName]}`:je&&(f.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),f.href.length>0&&f.click()})}static convertFrom(e,t,s){let o=e;if(e instanceof C){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case g.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER;break;case g.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case g.NOT_SUPPORTED:case g.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===g.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(me.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case g.DEVICE_NOT_FOUND:case g.DEVICE_AUTO_RECOVER_FAILED:a.code=U.DEVICE_ERROR;break;case g.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case g.SERVER_TIMEOUT:case g.SWITCH_ROLE_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case g.API_CALL_ABORTED:a.code=U.OPERATION_ABORT;break;case g.INITIALIZE_FAILED:a.code=5300,a.extraCode=nm(e.name);break;case g.UNKNOWN:break;default:a.code=U.OPERATION_FAILED}o=new hr(a),n&&(o.stack+=n.substr(n.indexOf(`
  27. `)))}else o=new hr({code:U.UNKNOWN_ERROR,fnName:t,originError:e});return o}};function nm(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var P=hr;var Zd={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},eu={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}}},mr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Y(r)){let t=document.getElementById(r);if(!t)throw new P({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}});if(!(t instanceof HTMLElement))throw new P({code:U.INVALID_PARAMETER,extraCode:5010,fnName:e,messageParams:{key:i,type:oe(t)}})}}},tu={name:"userId",required:!0,type:"string"},iu={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function xo(r,i){if(!r)throw new P({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function ru(r,i,e){if(!r)throw new P({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var ZI={type:"number",notLessThanZero:!0},am={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new P({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new P({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new P({code:U.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new P({code:U.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new P({code:U.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"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:mr,publish:{type:"boolean"},option:Zd},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Xt())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:M(N({},mr),{required:!1}),publish:{type:"boolean"},mute:{type:"boolean"},option:Zd}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:iu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Xt())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:iu}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:mr,publish:{type:"boolean"},option:eu},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&Xt())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!Zr())throw new P({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:mr,publish:{type:"boolean"},option:eu}},muteRemoteAudio:[tu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[tu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:mr,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(r,i,e){xo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(ru(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new P({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:M(N({},mr),{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(r,i,e){xo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(ru(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new P({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&T(r.streamType))throw new P({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){xo(this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Zt)throw new P({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new P({code:U.INVALID_OPERATION,messageParams:{key:O.SEI_DISABLED}});if(r.byteLength>1e3)throw new P({code:U.INVALID_PARAMETER,messageParams:{key:O.SEI_OVERSIZE,data:r.byteLength}});if(r.byteLength===0)throw new P({code:U.INVALID_PARAMETER,messageParams:{key:O.SEI_EMPTY}});if(xo(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new P({code:U.INVALID_PARAMETER,messageParams:{key:O.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},_e={TRTC:am};var ge=class extends Error{};function cm(r,i){let e=[];return lt(e,r),lt(e,i),e}function dm(r){this._resolve=Promise.resolve(r)}function um(r){this._reject=Promise.reject(r)}var pr=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=cm;let t=pr.instances.get(i);t?t.set(e,this):pr.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=pr.instances.get(i);return t&&t.get(e)||new pr(i,e)}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,u;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ge("start failed")),(u=this.currentOp)==null||u.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:dm,reject:um};try{switch(this.state){case 1:if(i===0)throw new ge("already started");break;case 4:if(i===2)throw new ge("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ge("already start");break;case 3:switch(i.type){case 2:throw new ge("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ge("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ge("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),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,i.args),this.lastOp.promise;case 3:throw new ge("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ge("start not allowed after update");case 0:throw new ge("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ge("keep start")),new ge("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.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}},Bt=pr;Bt.instances=new WeakMap;var wo=new WeakMap,Vo=(r,i)=>{if(i instanceof ge){let{stack:e}=i;i=new P({code:U.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
  28. `)))}throw i};function oi(r,i){return G((e,t)=>function(...s){let o=Bt.get(this,typeof r=="string"?r:r.call(this,...s));return i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Vo.bind(null,t))})}function Oi(r,i){let{merge:e,debounce:t}=i||{};return G((s,o)=>function(...n){let a=Bt.get(this,typeof r=="string"?r:r.call(this,...n));if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:u}=t;return new Promise((l,m)=>{var b,k;let f=(b=wo.get(this))==null?void 0:b.get(u(...n));if(f){let{timeoutId:ie,resolve:fe}=f;clearTimeout(ie),fe()}let I=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),n).catch(Vo.bind(null,o)).then(l,m)},c);wo.has(this)?(k=wo.get(this))==null||k.set(u(...n),{timeoutId:I,resolve:l}):wo.set(this,new Map([[u(...n),{timeoutId:I,resolve:l}]]))})}return a.action(2,s.bind(this),n).catch(Vo.bind(null,o))})}function ni(r){return G((i,e)=>function(...t){return Bt.get(this,typeof r=="string"?r:r.call(this,...t)).action(3,i.bind(this),t).catch(Vo.bind(null,e))})}var x={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",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",SEI_MESSAGE:"sei-message",STATISTICS:"statistics"};function nu(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function ms(r){return r===hs.QOS_PREFERENCE_CLEAR?"detail":r===hs.QOS_PREFERENCE_SMOOTH?"motion":""}function Uo(r){return{room:r,innerEmitter:E,constants:Bn,environment:Kt,utils:Ae,eventLogger:q,log:r.getLogger(),clearStarted(i,e){let t=i.getAlias(),s=Bt.instances.get(r);if(!!s)if(e){let o=s.get(t+e);if(!o)return;o.started=!1}else s.forEach((o,n)=>{n.startsWith(t)&&(o.started=!1)})}}}var au=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=D({key:O.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${o}
  29. ${s.stack}`),!1}},r};var Bo=new WeakMap;function cu(r,i){return G((e,t)=>function(...s){var a,c;let o=(a=Bo.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Bo.has(this)?(c=Bo.get(this))==null||c.set(i(...s),n):Bo.set(this,new Map([[i(...s),n]]))})}var du="5.2.1";function Re(...r){return G((i,e)=>function(...t){try{Fo.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function ec(...r){return G((i,e)=>function(...t){try{Fo.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Fo(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)$o.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else $o.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function $o({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new P(o(5001));if(T(r.defaultValue)){j(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let u=0;u<r.type.length;u++)r.type[u]===null&&i===null&&(c=!0),j(r.type[u])&&i instanceof r.type[u]&&(c=!0),Y(r.type[u])&&oe(i)===r.type[u].toLowerCase()&&(c=!0);if(!c)throw new P({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(u=>qr(u)?uo(u):Y(u)?u:oe(u))},value:i}})}else if(!T(r.type)&&oe(i)!==r.type)throw new P(o(5002));if(r.allowEmpty===!1){let c=Q(i)&&(i===0||Number.isNaN(i)),u=Y(i)&&i.trim()==="";if(c||u)throw new P(o(5003))}if(r.notLessThanZero&&Q(i)&&i<0)throw new P(o(5006));if(!T(r.min)&&Q(i)&&i<r.min)throw new P(o(5007));if(!T(r.max)&&Q(i)&&i>r.max)throw new P(o(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new P(o(5004))}else if(j(r.instanceOf)&&!(i instanceof r.instanceOf))throw new P(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new P(o(5005));let{properties:n}=r;Fe(n)&&Ii(i)&&Object.keys(n).forEach(c=>{$o.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Fe(a)&&de(i)&&i.forEach((c,u)=>{$o.call(this,{rule:a,value:c,key:`${e}[${u}]`,fnName:t,className:s})}),j(r.validate)&&r.validate.call(this,i,e,t,s,this)}function se(r={}){let{namePrefix:i=()=>"",getRemoteId:e=()=>""}=r;return G((t,s)=>function(...o){function n(m,f,I){if(I&&I.includes(m))return"hided";if(f===o||m in o)return f;try{return f instanceof HTMLElement?`id: ${f.id} type:${oe(f)}`:(JSON.stringify(f),f)}catch(b){return`type:${oe(f)}`}}let a=this._log||loggerManager,c=i.call(this,...o),l=c!==""?`${c}.${s}`:s;o.length>0?a.info(`${l}() ${JSON.stringify(o,(m,f)=>n(m,f,["userSig","privateMapKey"]))}`):a.info(`${l}()`);try{let m=t.apply(this,o),f=$();return Qr(m)?m.then(I=>(a.info(`${l}() success ${e.call(this,...o)}`),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,cost:$()-f}),I)).catch(I=>{throw I=P.convertFrom.call(this,I,l,o.length===1?o[0]:o),a.error(`${l}() failed ${e.call(this,...o)} ${I} params: ${JSON.stringify(o,n)}`),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,error:I}),I}):(E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,cost:$()-f}),m)}catch(m){throw m=P.convertFrom.call(this,m,l),a.error(`${l}() failed ${m} params: ${JSON.stringify(o,n)}`),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,error:m}),m}})}var Ho=r=>G((i,e)=>function(t,s){return p(this,null,function*(){let o=this._plugins.get(t);if(!o){this._log.warn(`plugin ${t} is not found`);return}return Fo.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Go=0,ps=class{constructor(i){this.core=i;d(this,"log");Go=Go+1,this.log=i.log.createChild({id:`${this.getAlias()}${Go}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Go}`),this.core=i}getName(){return"AudioMixer"}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ps.startValidateRule;case"update":return ps.updateValidateRule;case"stop":return ps.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.addMusicSource(i)})}update(i){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.updateMusicSource(i)})}stop(i){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.removeMusicSource(i)})}},Di=ps;d(Di,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url!=="*"){let s=["mp3","ogg","wav","flac"],o=i.url.split(".").pop(),n=s.indexOf(o)>=0,a=i.url.startsWith("blob"),c=i.url.startsWith("data");if(!(n||a||c))throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}}}),d(Di,"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"]}}}),d(Di,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}});var Wo=0,_s=class{constructor(i){this.core=i;d(this,"log");Wo=Wo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Wo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Wo}`)}getName(){return"AIDenoiser"}getAlias(){return"ad"}getGroup(i){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return _s.startValidateRule;case"update":return _s.updateValidateRule;case"stop":return _s.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core,{assetsPath:t,sdkAppId:s,userId:o,userSig:n}=i;if(t&&!e.audioManager.isDenoiserInit)try{yield e.audioManager.initDenoiser({assetsPath:t,sdkAppId:s,userId:o,userSig:n})}catch(a){if(a.message)throw new C({code:g.INVALID_PARAMETER,message:a.message})}yield e.audioManager.enableDenoiser(i),e.sendAbilityStatus({ai_denoise:1})})}update(i){return p(this,null,function*(){})}stop(i){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.disableDenoiser()})}},vi=_s;d(vi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{assetsPath:{type:"string",required:!0},sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}}}),d(vi,"updateValidateRule",{type:"object"}),d(vi,"stopValidateRule",{type:"object"});var uu=0,tc=new Set,we=null;Cn(du);var fs=class extends hu.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_log",A.createLogger({id:`t${++uu}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);this._room=new e(N({logger:this._log,frameWorkType:fs.frameWorkType},t)),t.plugins&&t.plugins.forEach(n=>{let a=new n(Uo(this._room));this._plugins.set(a.getName(),a)});let s=new Di(Uo(this._room));this._plugins.set(s.getName(),s);let o=new vi(Uo(this._room));this._plugins.set(o.getName(),o),this._room.on("audio-volume",n=>{!n.find(a=>a.userId==="")&&this._localAudioTrack&&n.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(x.AUDIO_VOLUME,{result:n.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",({reason:n,error:a})=>{this._log.error(new P({code:U.OPERATION_FAILED,extraCode:5504,messageParams:{reason:n,error:a}}))}),this.on(x.REMOTE_AUDIO_UNAVAILABLE,({userId:n})=>{this._stopRemoteAudio({userId:n},!1).catch(()=>{})}),this.on(x.REMOTE_VIDEO_UNAVAILABLE,({userId:n,streamType:a})=>{this._stopRemoteVideo({userId:n,streamType:a},!1).catch(()=>{})}),Te(ae,ae).add("audioInputAdded",n=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"add",device:n})}).add("audioInputRemoved",n=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"remove",device:n})}).add("videoInputAdded",n=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"add",device:n})}).add("videoInputRemoved",n=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"remove",device:n})}).add("audioOutputAdded",n=>p(this,null,function*(){if(this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"add",device:n}),we&&we.deviceId===Jr){let a=(yield nr()).find(c=>c.deviceId===Jr);a&&we.groupId!==a.groupId&&(we=a,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:a}))}})).add("audioOutputRemoved",n=>p(this,null,function*(){this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"remove",device:n});let a=(yield nr())[0];a&&we&&(we.deviceId===n.deviceId||we.deviceId===Jr&&we.groupId!==a.groupId)&&(we=a,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:a}))})),au(this,"trtc")}static create(e){}static _create(e,t){qd();let s=new fs(e,t||{});return tc.add(s),we?s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:we}):nr().then(o=>{o[0]&&(we=o[0],s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:o[0]}))}),s}enterRoom(e){return p(this,null,function*(){var c,u;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((u=(c=this._room).setTurnServer)==null||u.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,re(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,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};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),Te(this,this._room).add("peer-join",l=>{let{userId:m}=l;this.emit(x.REMOTE_USER_ENTER,{userId:m})}).add("peer-leave",l=>{this.emit(x.REMOTE_USER_EXIT,{userId:l})}).add("banned",l=>{this._exitRoom().then(()=>{this.emit(x.KICKED_OUT,{reason:l.reason})})}).add("error",l=>{this._exitRoom().then(()=>{this.emit(x.ERROR,P.convertFrom(l))})}).add("signal-connection-state-changed",l=>{this.emit(x.CONNECTION_STATE_CHANGED,l)}).add("network-quality",l=>{this._networkQuality=l,this.emit(x.NETWORK_QUALITY,l)}).add("remote-published",l=>{[l.remoteAudioTrack,l.remoteVideoTrack,l.remoteAuxiliaryTrack].forEach(f=>{Te(f,f).add("player-state-changed",I=>{let b=M(N({},I),{userId:l.userId});f.kind===h.VIDEO&&(b.streamType=nu(f.streamType)),this.emit(f.kind===h.AUDIO?x.AUDIO_PLAY_STATE_CHANGED:x.VIDEO_PLAY_STATE_CHANGED,b)}).add("error",I=>{I.getCode()===g.PLAY_NOT_ALLOWED&&this.emit(x.AUTOPLAY_FAILED,{userId:f.userId})})})}).add("remote-unpublished",l=>{[l.remoteAudioTrack,l.remoteVideoTrack,l.remoteAuxiliaryTrack].forEach(f=>{ne(f)})}).add("remote-publish-state-changed",({prevMuteState:l,muteState:m})=>{let{userId:f}=m,I=this._room.remotePublishedUserMap.get(f),b=l.audioAvailable,k=l.videoAvailable,{audioAvailable:ie,videoAvailable:fe}=m;ie||this._remoteAudioConfigMap.delete(f),fe||this._remoteVideoConfigMap.delete(`${f}_${"main"}`),m.hasAuxiliary||this._remoteVideoConfigMap.delete(`${f}_${"sub"}`),b!==ie&&this.emit(ie?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:f}),k!==fe&&this.emit(fe?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:f,streamType:"main"}),l.hasAuxiliary!==m.hasAuxiliary&&this.emit(m.hasAuxiliary?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:f,streamType:"sub"})}).add("firewall-restriction",()=>{this.emit(x.ERROR,new P({code:U.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",l=>{this.emit(x.SEI_MESSAGE,l)}).add("heartbeat-report",l=>{var I,b,k,ie,fe,ui,li;let m={2:"big",3:"small",7:"sub"},f={rtt:l.msg_up_stream_info.msg_network_status.uint32_rtt||((I=l.msg_down_stream_info[0])==null?void 0:I.msg_network_status.uint32_rtt)||((b=this._networkQuality)==null?void 0:b.uplinkRTT)||((k=this._networkQuality)==null?void 0:k.downlinkRTT)||0,upLoss:((ie=this._networkQuality)==null?void 0:ie.uplinkLoss)||0,downLoss:((fe=this._networkQuality)==null?void 0:fe.downlinkLoss)||0,bytesSent:l.bytes_sent||0,bytesReceived:l.bytes_received||0,localStatistics:{audio:{bitrate:(((ui=l.msg_up_stream_info.msg_audio_status)==null?void 0:ui.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((li=l.msg_up_stream_info.msg_audio_status)==null?void 0:li.uint32_audio_level)||0)/Xe},video:l.msg_up_stream_info.msg_video_status.filter(Ce=>m[Ce.uint32_video_stream_type]).map(Ce=>({bitrate:(Ce.uint32_video_codec_bitrate||0)/1e3,width:Ce.uint32_video_width,height:Ce.uint32_video_height,frameRate:Ce.uint32_video_enc_fps,videoType:m[Ce.uint32_video_stream_type]}))},remoteStatistics:l.msg_down_stream_info.map(Ce=>({userId:Ce.msg_user_info.str_identifier,audio:{bitrate:(Ce.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(Ce.msg_audio_status.uint32_audio_level||0)/Xe},video:Ce.msg_video_status.map(hi=>({bitrate:(hi.uint32_video_codec_bitrate||0)/1e3,width:hi.uint32_video_width,height:hi.uint32_video_height,frameRate:hi.uint32_video_dec_fps,videoType:m[hi.uint32_video_stream_type]}))}))};this.emit(x.STATISTICS,f)}),this._handleReceiveMode(),yield this._room.join(a,t,fs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e){return p(this,null,function*(){yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){ne(ae),this.removeAllListeners(),this._room.destroy(),tc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,option:s}=e,o=new ve(this._room.audioManager),n={},a={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(n.customSource=s.audioTrack):n.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&o.setCaptureVolume(s.captureVolume),T(s.profile)||(Y(s.profile)?eo[s.profile]&&o.setProfile(eo[s.profile]):o.setProfile(s.profile)),Q(s.earMonitorVolume)&&(a.muted=!(s.earMonitorVolume>0),a.volume=s.earMonitorVolume),T(s.echoCancellation)||(o.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(o.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(o.profile.autoGainControl=s.autoGainControl)),o.on("5",c=>{this.emit(x.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:c}}))}),o.on("2",c=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"active",device:c})}),o.on("4",c=>{let u;c.error&&(u=P.convertFrom(c.error)),this.emit(x.PUBLISH_STATE_CHANGED,M(N({},c),{error:u}))}),yield o.capture(n),Te(o,o).add("player-state-changed",c=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,M(N({},c),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),yield this._updateAudioPlayOption({playOption:a,track:o}),this._localAudioTrack=o,this._localAudioConfig=M(N({},e),{publish:t})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),lt(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),ne(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,option:o}=e,n=new ke(this._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:T(o.useFrontCamera)?T(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(o.profile)||(Y(o.profile)?yt[o.profile]&&n.setProfile(yt[o.profile]):n.setProfile(o.profile)),T(o.fillMode)||(c.objectFit=o.fillMode),T(o.mirror)||(c.mirror=o.mirror),T(o.small)||(_o()?Y(o.small)?n.small=yt[o.small]:n.small=o.small:this._log.warn("small stream is not supported"))),n.on("5",u=>{this.emit(x.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),n.on("2",u=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),n.on("4",u=>{let l;u.error&&(l=P.convertFrom(u.error)),this.emit(x.PUBLISH_STATE_CHANGED,M(N({},u),{error:l}))}),yield n.capture(a),(o==null?void 0:o.qosPreference)&&n.mediaTrack){let u=ms(o.qosPreference);n.mediaTrack.contentHint=u}Te(n,n).add("player-state-changed",u=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,M(N({},u),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),yield this._updateVideoPlayOption({view:t,playOption:c,track:n}),this._localVideoTrack=n,this._localVideoConfig=M(N({},e),{view:t,publish:s})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n&&(T(n.profile)||(Y(n.profile)?yt[n.profile]&&this._localVideoTrack.setProfile(yt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack)){let c=ms(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}this._room.isJoined&&!T(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||this._localVideoTrack.setMute(o),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),lt(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ne(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:o}=e,n=new xe(this._room.videoManager);n.on("4",m=>{let f;m.error&&(f=P.convertFrom(m.error)),this.emit(x.PUBLISH_STATE_CHANGED,M(N({},m),{error:f}))});let a=null;n.setMediaType(2);let c={},u={};o&&(T(o.profile)||(Y(o.profile)?to[o.profile]&&n.setProfile(to[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(o.fillMode)||(u.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack));let l=yield n.capture(c);if(o!=null&&o.qosPreference){let m=ms(o.qosPreference);n.mediaTrack.contentHint=m}if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(x.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new xt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0])),Te(n,n).add("player-state-changed",m=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,M(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[n];a&&m.push(a),this._room.publish(...m).catch(()=>{})}yield this._updateVideoPlayOption({view:t,playOption:u,track:n}),this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=M(N({},e),{view:t,publish:s})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=ms(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!T(s)&&(s&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenConfig.publish&&!s&&this._room.unpublish(this._localScreenTrack).catch(()=>{})),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),lt(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let u={},l=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror),o==="main"&&!T(n.small)&&this._room.changeType(n.small,l.user)),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:u,track:l}),this._remoteVideoConfigMap.set(a,e)})}updateRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(!this._remoteVideoConfigMap.has(a)||!this._room.remotePublishedUserMap.has(s))return;let c={};n&&(T(n.fillMode)||(c.objectFit=n.fillMode),T(n.mirror)||(c.mirror=n.mirror));let u=null,l=this._room.remotePublishedUserMap.get(s);o==="main"&&(l==null?void 0:l.muteState.hasVideo)&&(u=l.remoteVideoTrack),o==="sub"&&(l==null?void 0:l.muteState.hasAuxiliary)&&(u=l.remoteAuxiliaryTrack);let m=this._remoteVideoConfigMap.get(a);u&&(o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:c,track:u,prevConfig:m})),lt(m,e)})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&s.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&s.push(c))}for(let n of s)t&&(yield this._room.unsubscribe(n));this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return p(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return super.on(e,t,s),this._eventListened.add(e),this}off(e,t,s){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let o=this._room.remotePublishedUserMap.get(t);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let t=this._room.remotePublishedUserMap.get(e);if(t)return t.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var t;(t=this._localAudioTrack)==null||t.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return p(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(T(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a}),this._remoteAudioConfigMap.set(t,e)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack))),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(T(e)&&o&&o.view&&!Xr(t)){let a;de(o.view)?a=o.view:a=lo(o.view),a&&(yield s.play(a,t))}if(!T(e)){let a;de(e)?a=e:a=lo(e),a?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100)})}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_handleReceiveMode(){this._room.autoReceiveAudio&&Te(this,this).add(x.REMOTE_AUDIO_AVAILABLE,t=>p(this,[t],function*({userId:e}){if(this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e))return;let s=this._room.remotePublishedUserMap.get(e);s&&(yield this._room.subscribe(s.remoteAudioTrack).catch(()=>{}),yield this._updateAudioPlayOption({track:s.remoteAudioTrack}).catch(()=>{}),this._remoteAudioConfigMap.set(e,{userId:e}))})),this._room.autoReceiveVideo&&Te(this,this).add(x.REMOTE_VIDEO_AVAILABLE,({userId:e,streamType:t})=>{let s=this._room.remotePublishedUserMap.get(e);s&&(t==="main"?this._room.subscribe(s.remoteVideoTrack).catch(()=>{}):t==="sub"&&this._room.subscribe(s.remoteAuxiliaryTrack).catch(()=>{}))})}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{ne(e.remoteAudioTrack),ne(e.remoteVideoTrack),ne(e.remoteAuxiliaryTrack)}),ne(this)})}_stopScreenShare(){return p(this,null,function*(){var e,t,s;if(!!this._localScreenTrack){if(this._room.isJoined){let o=[this._localScreenTrack];this._localScreenAudioTrack&&o.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...o).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),(t=this._localScreenAudioTrack)==null||t.stop(),(s=this._localScreenAudioTrack)==null||s.close(),ne(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}})}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}static setLogLevel(e,t){A.setLogLevel(e),T(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return jn()}static getCameraList(){return Ge()}static getMicrophoneList(){return Pe()}static getSpeakerList(){return nr()}static setCurrentSpeaker(e){return p(this,null,function*(){(yield nr()).forEach(s=>{s.deviceId===e&&(tc.forEach(o=>{o.setCurrentSpeaker(e),o.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),we=s)})})}},J=fs;d(J,"_loggerManager",A),d(J,"EVENT",x),d(J,"ERROR_CODE",U),d(J,"TYPE",hs),d(J,"frameWorkType",30),y([Re(_e.TRTC.enterRoom),oi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),G(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i).catch(e=>{throw ne(this),e})}),se()],J.prototype,"enterRoom",1),y([se()],J.prototype,"exitRoom",1),y([Re(_e.TRTC.switchRole),Oi("room",{merge:(r,i)=>i}),se()],J.prototype,"switchRole",1),y([se()],J.prototype,"destroy",1),y([Re(_e.TRTC.startLocalAudio),oi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),se()],J.prototype,"startLocalAudio",1),y([Re(_e.TRTC.updateLocalAudio),Oi("audio",{debounce:{delay:200,getKey:()=>`${uu}-localAudio`,isNeedToDebounce:r=>{var i;return!T((i=r.option)==null?void 0:i.captureVolume)}}}),se()],J.prototype,"updateLocalAudio",1),y([ni("audio"),se()],J.prototype,"stopLocalAudio",1),y([Re(_e.TRTC.startLocalVideo),oi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),se()],J.prototype,"startLocalVideo",1),y([Re(_e.TRTC.updateLocalVideo),Oi("video"),se()],J.prototype,"updateLocalVideo",1),y([ni("video"),se()],J.prototype,"stopLocalVideo",1),y([Re(_e.TRTC.startScreenShare),oi("screen",()=>!0),se()],J.prototype,"startScreenShare",1),y([Re(_e.TRTC.updateScreenShare),Oi("screen"),se()],J.prototype,"updateScreenShare",1),y([se()],J.prototype,"stopScreenShare",1),y([Re(_e.TRTC.startRemoteVideo),oi(r=>`v${r.userId}${r.streamType}`,()=>!0),se({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"startRemoteVideo",1),y([Re(_e.TRTC.updateRemoteVideo),Oi(r=>`v${r.userId}${r.streamType}`),se({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"updateRemoteVideo",1),y([Re(_e.TRTC.stopRemoteVideo),G(r=>function(i){return p(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),se({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"stopRemoteVideo",1),y([ni(r=>`v${r.userId}${r.streamType}`)],J.prototype,"_stopRemoteVideo",1),y([Re(..._e.TRTC.muteRemoteAudio),se({getRemoteId:r=>r})],J.prototype,"muteRemoteAudio",1),y([ec(..._e.TRTC.setRemoteAudioVolume),cu(200,r=>r),se({getRemoteId:r=>r})],J.prototype,"setRemoteAudioVolume",1),y([Ho("start"),oi((r,i)=>r.getAlias()+r.getGroup(i)),se({namePrefix:r=>r.getName()})],J.prototype,"startPlugin",1),y([Ho("update"),Oi((r,i)=>r.getAlias()+r.getGroup(i)),se({namePrefix:r=>r.getName()})],J.prototype,"updatePlugin",1),y([Ho("stop"),ni((r,i)=>r.getAlias()+r.getGroup(i)),se({namePrefix:r=>r.getName()})],J.prototype,"stopPlugin",1),y([ec(..._e.TRTC.enableAudioVolumeEvaluation)],J.prototype,"enableAudioVolumeEvaluation",1),y([oi(r=>`a${r.userId}`,()=>!0)],J.prototype,"_startRemoteAudio",1),y([G(r=>function(i){return p(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(M(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),ni(r=>`a${r.userId}`)],J.prototype,"_stopRemoteAudio",1),y([ni("room")],J.prototype,"_exitRoom",1),y([ni("screen")],J.prototype,"_stopScreenShare",1),y([Re(_e.TRTC.sendSEIMessage),Yd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],J.prototype,"sendSEIMessage",1),y([Re(_e.TRTC.create)],J,"_create",1);var Es=J;var ic=class{constructor(){this._set=new Set;E.on(_.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function hm(){return p(this,null,function*(){let r,i;try{let m=yield Pe();r=m&&m.length}catch(m){}try{let m=yield Ge();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Dt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},u={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};q.uploadEvent({log:`trtcstats-${JSON.stringify(u)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(u)}`),q.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function mu(){return G(r=>{let i=new ic;return function(e,t,s){return p(this,null,function*(){let o=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=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new C({code:g.INVALID_OPERATION,message:D({key:O.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new C({code:g.INVALID_OPERATION,message:D({key:O.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),E.emit(_.JOIN_START,{room:this,roomId:o,params:e}),this.checkSystemResult=yield Dt.checkSystemRequirementsInternal(),this.checkDestroy();let n=Ae.getEnv();n||(n=Nt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(io.OLD_CLOUD_LADDER)?n=Nt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(io.WEBRTC)&&(n=Nt.WEBRTC))),q.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),hm.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Dt.isWebRTCSupported()||!a&&!c)throw new C({code:g.NOT_SUPPORTED,message:D({key:O.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ae.getEnv()&&(yield this.schedule(o,s,Ie));let u=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=Ae.performanceNow(),E.emit(_.JOIN_SUCCESS,{room:this}),q.uploadEvent({log:`stat-conv-${Number(Ye)}-${location.hostname}`,userId:this.userId}),u}catch(u){throw i.delete({room:this,roomId:o}),E.emit(_.JOIN_FAILED,{room:this,error:u}),u}})}})}var pu=()=>G(r=>function(...i){return p(this,null,function*(){E.emit(_.LEAVE_START,{room:this}),yield r.call(this),E.emit(_.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function _u(){return G(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Eu=Ne(Me());var ce={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4"},Ve={DISCONNECTED:"DISCONNECTED",CONNECTING:"CONNECTING",CONNECTED:"CONNECTED"},Tt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158},fu=[Tt.UPDATE_REMOTE_MUTE_STAT,Tt.UPLINK_NETWORK_STATS,Tt.USER_LIST_RES,Tt.MUTE_RESULT],B={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report"};var Ko=new Set;function Tu(r){let i=[...Ko.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Ts=class extends Eu.default{constructor(e){var s,o;super();d(this,"room");d(this,"url");d(this,"backupUrl");d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_backupTimer",-1);d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});d(this,"_currentState",Ve.DISCONNECTED);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_prevTime",-1);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);this.room=e.room,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Ko.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Ko.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=A.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId})}get urlParam(){return`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`}get _urlWithParam(){return`${this.url}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.urlParam}`}get isConnected(){return this._currentState===Ve.CONNECTED}get isConnecting(){return this._currentState===Ve.CONNECTING}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState===Ve.CONNECTED&&Date.now()-this._lastMessageTime<12*1e3}connect(e){return this.isConnected?Promise.resolve():new Promise((t,s)=>{this._prevTime<0&&(this._prevTime=$()),this._log.info(`connect to ${this.url}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged(Ve.CONNECTING),this._socket=new WebSocket(this._urlWithParam),this.bindSocket(this._socket),this._backupTimer=setTimeout(()=>{this.isConnected||(this._log.info("trying to connect to backupUrl"),this.tryConnectBackup())},5e3);let o=-1;e&&(o=setTimeout(()=>{this.close(),s(new C({code:g.JOIN_ROOM_FAILED,message:"join room timeout"}))},e)),this.once(ce.CONNECTED,()=>{clearTimeout(o),t()}),this.once(ce.RECONNECT_FAILED,n=>{clearTimeout(o),s(n)})})}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(h.MAIN),this._log.debug(`try to connect to url: ${this._backupUrlWithParam}`),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(e){e.onopen=this.onopen.bind(this),e.onclose=this.onclose.bind(this),e.onerror=this.onerror.bind(this),e.onmessage=this.onmessage.bind(this)}unbindSocket(e){this.clearBackupTimer(),e.onopen=()=>{},e.onclose=()=>{},e.onerror=()=>{},e.onmessage=()=>{}}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}clearBackupTimer(){this._backupTimer!==-1&&(clearTimeout(this._backupTimer),this._backupTimer=-1)}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onopen(e){if(this.isConnected)return;this.isReconnecting&&!this._signalInfo.tinyId&&this.stopReconnection(),this.clearBackupTimer(),e.target===this._socket?(this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(h.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(Ve.CONNECTED),this.emit(ce.CONNECTED)}onclose(e){let{url:t}=e.target,s=e.target===this._socketInUse;if(this._log.info(`websocket[${t} InUse: ${s}] is closed with code: ${e.code}`),s&&(this.emitConnectionStateChanged(Ve.DISCONNECTED),!e.wasClean||e.code!==1e3)){this._log.warn(`onclose code:${e.code} reason:${e.reason}`),this._log.warn("close current websocket and schedule a reconnect timeout"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011);let o=this._socketInUse===this._socket;this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(o?h.BACKUP:h.MAIN)}}onerror(e){let{url:t}=e.target;if(this._log.error(`websocket[${t}] error observed`),!this.isConnected)this.isReconnecting||E.emit(_.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),e.target==this._socket?(this.unbindAndCloseSocket(h.MAIN),this.reconnect(h.BACKUP)):(this.unbindAndCloseSocket(h.BACKUP),this.reconnect(h.MAIN));else if(e.target===this._socketInUse){this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP);let s=this._socketInUse===this._socket;this._socketInUse=null,this.reconnect(s?h.BACKUP:h.MAIN)}}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=ho(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(Tt),c=Object.keys(Tt)[n.indexOf(s)],u=B[c];switch(fu.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case Tt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,this._signalInfo.tinyId=t.tinyId,o.svrTime&&Vc(o.svrTime),this._log.info("ChannelSetup Success"),E.emit(_.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",cost:$()-this._prevTime}),this._prevTime=-1,this.emit(ce.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:g.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:D({key:O.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),E.emit(_.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",error:l}),this.emit(ce.SETUP_FAILED,l)}break}case Tt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:t});break}case Tt.CHANNEL_RECONNECT_RESULT:{t.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),E.emit(_.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketReconnect",cost:$()-this._prevTime}),this._prevTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(this._log.warn(`reconnect failed, ${t.code} ${t.message}`),this.room.reJoin());break}default:this.emit(u,{data:t});break}}reconnect(e=h.MAIN){if(!this.room.isJoined&&this.keepAlive){this.close();return}if(this.isReconnecting)return;if(this._reconnectionCount>=Wr){this._log.warn(`SDK has tried reconnect signal channel for ${Wr} times, but all failed. please check your network`);let o=new C({code:g.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:D({key:O.SIGNAL_CHANNEL_RECONNECTION_FAILED})});E.emit(_.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketReconnect",error:o}),this.emit(ce.RECONNECT_FAILED,o);return}this._reconnectionCount++,this._log.warn(`reconnect ${e} [${this._reconnectionCount}/${Wr}]`);let t=this.getReconnectionUrl(e);this.emitConnectionStateChanged(Ve.CONNECTING),this._prevTime<0&&(this._prevTime=$()),e===h.MAIN?(this._socket=new WebSocket(t),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(t),this.bindSocket(this._backupSocket));let s=He(this._reconnectionCount);this._reconnectionTimer=setTimeout(()=>{this._log.warn(`reconnect ${e} timeout(${s/1e3}s), try again`),this.clearReconnectionTimer(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.reconnect(e===h.MAIN?h.BACKUP:h.MAIN)},s)}get isReconnecting(){return this._reconnectionTimer!==-1}getReconnectionUrl(e){let t=e===h.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&t.indexOf("&rc=1")===-1){let{roomId:s,useStringRoomId:o}=this.room;t+=`&rc=1&relayInnerIp=${this._signalInfo.relayInnerIp}&relayOuterIp=${this._signalInfo.relayIp}&relayPort=${this._signalInfo.relayPort}&roomId=${s}&useStringRoomId=${o}`}return t}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=ho(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,u)=>{let l=setTimeout(()=>{this.off(o,m);let I=new C({code:g.API_CALL_TIMEOUT,message:D({key:O.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(I),u(I)},s),m=I=>{I.data.seq===f&&(clearTimeout(l),this.off(o,m),c(I))};this.on(o,m);let f=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return ht({retryFunction:this.sendWaitForResponse,onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this.isReconnecting&&(this._reconnectionCount=0,this.clearReconnectionTimer())}close(){this._log.info("closed"),Ko.delete(this),this.clearBackupTimer(),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged(Ve.DISCONNECTED)}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close()},e*1e3),s=o=>{o instanceof Ri&&o.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(L.STATECHANGED,s))};this.room.on(L.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(ce.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e)}};var gu=Ne(Me());var gs=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var rc=class{constructor(i,e,t){this._connection=i;this._log=e;this._isUplink=t;d(this,"_seiMessageList",[]);d(this,"_seiPayloadType",243);d(this,"_mainVideoSenderOrReceiver",null);d(this,"_mainVideoAbortController",null);d(this,"_abortMap",new Map);d(this,"onSEIMessage")}get isRunning(){return!!this._mainVideoAbortController}start(i){this._mainVideoSenderOrReceiver=i;let e=i.createEncodedStreams(),t=e.readable,s=e.writable,o=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,t.pipeThrough(o).pipeTo(s,this._mainVideoAbortController).catch(()=>{})}restart(i){this.stop(),this.start(i)}stop(){var i;(i=this._mainVideoAbortController)==null||i.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach(i=>i.abort()),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let i=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(i),this._isUplink?i.getSenders().forEach((e,t)=>{if(t===1){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}}):i.getReceivers().forEach((e,t)=>{var s;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(t===1&&((s=e.track)==null?void 0:s.kind)===h.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))})}catch(i){this._log.warn(i)}}pipeSenderOrReceiver(i){let{readable:e,writable:t}=i.createEncodedStreams(),s=new AbortController;this._abortMap.set(i,s),e.pipeTo(t,s).catch(()=>{})}clearUnusedSenderOrReceiver(i){this._abortMap.forEach((e,t)=>{(this._isUplink?i.getSenders():i.getReceivers()).find(o=>o===t)||(e.abort(),this._abortMap.delete(t))})}push(i,e){e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i)}hasSEI(i){let e=new DataView(i);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(i){return i.type==="empty"||i.data.byteLength===0}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encodeVideoFrame(i,e){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(i)){let t=this.getNaluCount(i.data),s=9-t;if(s<=0)return;let o=this._seiMessageList.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),n=o.reduce((m,f)=>m+f.dataView.byteLength,0),a=new ArrayBuffer(n+i.data.byteLength),c=new DataView(a),u=new DataView(i.data),l=0;for(let m=0;m<o.length;m++)for(let f=0;f<o[m].dataView.byteLength;f++)c.setInt8(l++,o[m].dataView.getInt8(f));for(let m=0;m<i.data.byteLength;m++)c.setInt8(l++,u.getInt8(m));i.data=a,this._log.debug(`${o.length} sei sent`)}}catch(t){this._log.warn(t)}e.enqueue(i)}decodeVideoFrame(i,e){try{if(this._connection.isH264&&!this.isEmptyFrame(i)&&this.hasSEI(i.data)){let t=[],s=new DataView(i.data),o=0,n=-1,a=-1;for(let c=0;c<i.data.byteLength;c++){let u=s.getUint8(c);if(u===0)o++;else if(u===1){if(o===2||o===3){let l=c-o;if(n===-1?n=l:a===-1&&(a=l,t.push(new gs(new DataView(s.buffer.slice(n,a)))),n=l,a=-1),!(s.getUint8(c+1)===6)){i.data=new DataView(s.buffer.slice(l)).buffer;break}}o=0}else o=0}this._log.debug(`${t.length} sei received`),j(this.onSEIMessage)&&t.reverse().forEach(c=>{this.onSEIMessage({seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer})})}}catch(t){this._log.warn(t)}e.enqueue(i)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(e/255),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new gs(new DataView(new Uint8Array(o).buffer),!0)}},Jo=rc;var sc=0,oc=!1,jo=new Set,mm=r=>sc>2&&!oc&&jo.size===0&&r,nc=!1,Ue=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new gu.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_enableSEI");d(this,"_sei");d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=A.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI,this._enableSEI&&Zt&&(this._sei=new Jo(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=$())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min($()-this._prevTime,30*1e3)})):this._isReconnecting&&E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:$()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:e})):this._isReconnecting&&this._reconnectionCount>=3&&E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Zt,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),jo.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new C({code:g.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return qe;let i=null;if(this._isUplink){if(!sr()||this._peerConnection.getSenders().length===0)return qe;i=this._peerConnection.getSenders()[0].transport}else{if(!Ai()||this._peerConnection.getReceivers().length===0)return qe;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:qe}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===te.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===te.FAILED||i.target.connectionState===te.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new C({message:s,code:g.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===te.CONNECTED||i.target.connectionState===te.COMPLETED)&&(this.logSelectedCandidate(),q.logSuccessEvent({userId:this._room.userId,eventType:be.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(sc=0,oc=!1,nc=!0,jo.add(this)):jo.delete(this),E.emit(_.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(zt(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new C({code:g.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{E.off(_.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new C({code:g.API_CALL_TIMEOUT,message:"connection timeout"});sc+=1,mm(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),oc=!0,this._emitter.emit("firewall-restriction")),e(a)},Kr);E.on(_.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ce.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ot()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?g.UPLINK_RECONNECTION_FAILED:g.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?O.UPLINK_RECONNECTION_FAILED:O.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(ce.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var uc=Ne(dc());var ue=function(r){return uc.default.parse(r)},We=function(r){return uc.default.write(r)},bu=function(r){let i=ue(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),We(i)};function Ou(r){let i=ue(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let u=c.match(/apt=(\d+)/);u&&u[1]&&o.has(Number(u[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),We(i)}function Yo(r){return Object.keys(r).filter(i=>r[i])}var hc=class extends Ue{constructor(e){super(M(N({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new wt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ft(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new cr(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Qt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===Gr?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
  30. `),s=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...s];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
  31. `)}addSPSDescription(e){let t=ue(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),We(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=ue(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),We(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===te.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===te.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new C({code:g.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Yo(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:O.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:B.SUBSCRIBE_RESULT,timeout:wn});if(!this._peerConnection){let a=new C({code:g.INVALID_OPERATION,message:D({key:O.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};et()&&this._sdpSemantics===jt?(this._peerConnection.addTransceiver(h.AUDIO,{direction:K.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:K.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:K.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield po();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=Ou(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=bu(t.sdp),this._sdpSemantics===jt&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Ei)throw new C({code:g.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new C({code:t,message:D({key:O.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",M(N({},a),{userId:this.userId}))}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ue(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Gr)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Gr)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(kn)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return p(this,null,function*(){if(!(At(hc.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=He(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}},Is=hc;y([G(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new C({code:g.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Is.prototype,"subscribe",1),y([Ao(Ue.prototype.afterConnect),Io(Ue.prototype.beforeConnect)],Is.prototype,"connect",1);var lc=Is;var vu={voiceActivityDetection:!1},mc=class extends Ue{constructor(e){super(M(N({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_audioManager");this._audioManager=e.audioManager}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(mt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),et()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,u=this._audioManager.mixedAudioTrack;u&&a.addTrack(u),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(u||h.AUDIO,{direction:K.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:K.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:K.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:K.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(u&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(u),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let f=o?3:1;yield l[f].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),m.push(f),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(K.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=this._audioManager.mixedAudioTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),s)){let u=new MediaStream;u.addTrack(s),this._peerConnection.addTrack(s,u)}yield this.connect()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!mt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(this._audioManager.mixedAudioTrack||(yield a[0].replaceTrack(null),c.push(0)),o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=M(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=M(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(K.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===g.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),tt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){var s;if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),et()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===K.INACTIVE&&(yield this.setTransceiverDirection(K.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;mt()&&this._peerConnection.getTransceivers().findIndex(n=>n.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let n=s.track;this.removeSender(s),yield this.updateOffer("remove",n)}let o=t.kind===h.VIDEO?t:this._audioManager.mixedAudioTrack;if(o&&this._peerConnection.addTrack(t,new MediaStream([o])),t.kind===h.VIDEO&&e instanceof ke&&e.small){let n=new MediaStream,a=this._room.videoManager.smallTrack;n.addTrack(a),this._peerConnection.addTrack(a,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Qi||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ue(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;mt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&j(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),et()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)this._audioManager.mixedAudioTrack||(yield s[0].sender.replaceTrack(null));else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(K.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!X)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(u=>{n[u].direction!==e&&(n[u].direction=e,s=!0)}),s){this._log.info("updating offer");let u=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(u)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
  32. `).map(u=>{if(u.match(new RegExp(`a=(${K.INACTIVE}|${K.RECVONLY}|${K.SENDONLY})`))&&a++,t.includes(a)){if(e===K.INACTIVE&&u.includes(`a=${K.RECVONLY}`))return o=!0,`a=${e}`;if(e===K.SENDONLY&&u.includes(`a=${K.INACTIVE}`))return o=!0,`a=${K.RECVONLY}`}return u}).join(`\r
  33. `);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===h.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(s=>s.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===h.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(s=>{s.track&&s.track.kind===h.VIDEO&&this.removeSender(s)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return;let s;if(et()?s=e.kind===h.AUDIO?t[0]:t[1]:s=t.find(a=>a.track&&a.track.kind===e.kind),!s)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${e.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(this._audioManager.mixedAudioTrack):e.kind===h.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack))})}updateOffer(e,t){return p(this,null,function*(){try{let s=yield this._peerConnection.createOffer(vu);X&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_CHANGE,data:n,responseCommand:B.UPDATE_OFFER_RESULT,timeout:xn,commandDesc:"update offer"}),{code:c,message:u}=a.data;c!==0&&this.checkPublishResultCode(c,u),yield this.acceptAnswer(a.data.data),s.sdp&&this.updateSSRC(s.sdp)}catch(s){throw this._log.error(s),s}})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s,sdp:o}){if(!ts())return o?t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e):void 0;let a=0;t===h.VIDEO&&(s===h.SMALL?a=2:s===h.AUXILIARY?a=3:a=1);let c=this._peerConnection.getSenders()[a];if(c){let u=c.getParameters();(!u.encodings||u.encodings.length===0)&&(u.encodings=[{}]),u.encodings[0].maxBitrate=e*1e3;try{return yield c.setParameters(u),this._log.info(`${s||""}${t} bandwidth ${e} kbps`),o}catch(l){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${l}`),o)return t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,s){let o="AS";X&&(o="TIAS",t=t*1e3);let n=0,a=-1;return s===h.SMALL?n=1:s===h.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${o}:${t}\r
  34. `:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return X&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
  35. c=IN $2\r
  36. b=${s}:${t}\r
  37. `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return p(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return p(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return p(this,null,function*(){try{let e=yield this._peerConnection.createOffer(vu);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:W.PUBLISH,responseCommand:B.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof xe||this.localAuxVideoTrack instanceof xe,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:o,data:n}=t.data;return s===0?this.acceptAnswer(n):this.checkPublishResultCode(s,o)})}setSDPDirection(e,t,s="all"){let o=ue(e);return o.media.forEach(n=>{(s==="all"||n.type===s)&&(n.direction=t)}),We(o)}acceptAnswer(e){return p(this,null,function*(){var t,s,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),f=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let I=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:I})}f&&(c=yield this.setBandwidth({bandwidth:f,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:m}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||m.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:c})}let l={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(l),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(W.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(At(mc.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,responseCommand:B.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=He(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(_.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ue(e).media.forEach((s,o)=>{if(s.type===h.AUDIO){let n=s.ssrcs&&s.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Qi&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let u=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=u:c===1&&(this.ssrc.small=u)});return}let n=s.ssrcs&&s.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Ei?(this._log.error(me.NOT_SUPPORTED_H264ENCODE),new C({code:g.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264ENCODE})})):new C({code:g.UNKNOWN,message:D({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}},As=mc;y([G(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new C({code:g.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],As.prototype,"publish",1),y([Ao(Ue.prototype.afterConnect),Io(Ue.prototype.beforeConnect)],As.prototype,"connect",1);var Qo=As;var Rs=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime");d(this,"_prevReport",{});d(this,"_prevEncoderImplementation");d(this,"_prevQualityLimitationReason");d(this,"_prevAuxQualityLimitationReason");d(this,"_prevDecoderImplementationMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(n=>{if(n.type==="outbound-rtp")if((n.mediaType||n.kind)===h.VIDEO){let c,u;if(n.ssrc===s.video?(c=h.VIDEO,u=i.localMainVideoTrack):n.ssrc===s.small?c=h.SMALL:n.ssrc===s.auxiliary&&(u=i.localAuxVideoTrack,c=h.AUXILIARY),!c)return;e[c].bytesSent=n.bytesSent,e[c].packetsSent=n.packetsSent,e[c].framesEncoded=n.framesEncoded,T(n.keyFramesEncoded)||(e[c].keyFramesEncoded=n.keyFramesEncoded),T(n.nackCount)||(e[c].nackCount=n.nackCount),T(n.pliCount)||(e[c].pliCount=n.pliCount),T(n.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=n.retransmittedPacketsSent),T(n.totalEncodeTime)||(e[c].totalEncodeTime=n.totalEncodeTime),T(n.totalPacketSendDelay)||(e[c].totalPacketSendDelay=n.totalPacketSendDelay),n.ssrc===s.video?(!T(n.encoderImplementation)&&this._prevEncoderImplementation!==n.encoderImplementation&&(this._log.info(`encoderImplementation change to ${n.encoderImplementation}`),this._prevEncoderImplementation=n.encoderImplementation),!T(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${n.qualityLimitationReason}`),this._prevQualityLimitationReason=n.qualityLimitationReason)):n.ssrc===s.auxiliary&&!T(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevAuxQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${n.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=n.qualityLimitationReason)}else e.audio.bytesSent=n.bytesSent,e.audio.packetsSent=n.packetsSent;else n.type==="candidate-pair"?zt(n)&&Q(n.currentRoundTripTime)&&(e.rtt=Math.floor(n.currentRoundTripTime*1e3),this.totalBytesSent=n.bytesSent):n.type==="media-source"&&(n.kind===h.AUDIO?(e.audio.audioLevel=n.audioLevel||0,e.audio.totalAudioEnergy=n.totalAudioEnergy||0):n.kind===h.VIDEO&&(n.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=n.framesPerSecond:n.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=n.framesPerSecond:e.small.fpsCapture=n.framesPerSecond));if(T(n.audioLevel)||(e.audio.audioLevel=n.audioLevel||0),!T(n.frameWidth)){let a=h.SMALL;n.trackIdentifier===i.getVideoTrackId(h.VIDEO)||n.ssrc===s.video?a=h.VIDEO:(n.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||n.ssrc===s.auxiliary)&&(a=h.AUXILIARY),e[a].frameWidth=n.frameWidth,e[a].frameHeight=n.frameHeight,e[a].framesSent=n.framesSent}}),i.localMainAudioTrack){let n=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=n,e.audio.audioLevel===0&&(e.audio.audioLevel=n)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent)}catch(o){this._log.warn(`failed to getStats on sender connection ${o}`)}return e})}getReceiverStats(i){return p(this,null,function*(){let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},t=i.getPeerConnection();if(t)try{let{ssrc:s}=i,{muteState:o,subscribeState:n}=i;(this._spcStats||(yield t.getStats())).forEach(c=>{if(c.type==="inbound-rtp")if((c.mediaType||c.kind)===h.AUDIO){if(c.ssrc!==s.audio||!o.hasAudio)return;e.audio.packetsReceived=c.packetsReceived,e.audio.bytesReceived=c.bytesReceived,e.audio.packetsLost=c.packetsLost,c.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=c.insertedSamplesForDeceleration),c.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=c.removedSamplesForAcceleration);let{remoteAudioTrack:l}=i;l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,c.jitterBufferDelay&&(l.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)),e.hasAudio=!0}else{if(X&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&o.hasVideo&&(e.video.packetsReceived=c.packetsReceived,e.video.bytesReceived=c.bytesReceived,e.video.packetsLost=c.packetsLost,e.video.framesReceived=c.framesReceived,e.video.framesDecoded=c.framesDecoded,e.video.fpsDecoded=c.framesPerSecond,e.hasVideo=!0,l=i.remoteVideoTrack,o.hasSmall&&n.smallVideo&&(e.isSmallSubscribed=!0),c.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==c.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${c.decoderImplementation}`),this._prevDecoderImplementationMap.set(e.userId,c.decoderImplementation))),c.ssrc===s.auxiliary&&o.hasAuxiliary&&(e.auxiliary.packetsReceived=c.packetsReceived,e.auxiliary.bytesReceived=c.bytesReceived,e.auxiliary.packetsLost=c.packetsLost,e.auxiliary.framesReceived=c.framesReceived,e.auxiliary.framesDecoded=c.framesDecoded,e.auxiliary.fpsDecoded=c.framesPerSecond,l=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),l&&(l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,l.stat.framesReceived=c.framesReceived,l.stat.framesDecoded=c.framesDecoded,c.jitterBufferDelay&&(l.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)))}else c.type==="candidate-pair"&&zt(c)&&Q(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);T(c.frameWidth)||((c.trackIdentifier===i.getMainStreamVideoTrackId()||c.ssrc===s.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,i.remoteVideoTrack.stat.frameWidth=c.frameWidth,i.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===i.getAuxStreamVideoTrackId()||c.ssrc===s.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=c.frameHeight)),T(c.audioLevel)||(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(s){this._log.warn(`failed to getStats on receiver connection ${s}`)}return e})}getStats(i,e){return p(this,null,function*(){let t={},s=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:s};let n=yield o.getStats(),a=[],c=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach(u=>c.has(u.type)&&a.push(u)),this._spcStats=a}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Pt(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){if(!Pt(i.senderStats)){let l={uint32_audio_level:i.senderStats.audio.audioLevel*Xe,uint32_audio_energy:i.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(l.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Xe);let m=[];if(i.senderStats.video.bytesSent){let I={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};m.push(I)}if(i.senderStats.small.bytesSent){let I={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};m.push(I)}if(i.senderStats.auxiliary.bytesSent){let I={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};m.push(I)}let f={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:l,msg_video_status:m,msg_network_status:f}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(l=>{let m={msg_user_info:{str_identifier:l.userId,uint64_tinyid:l.tinyId},msg_network_status:{uint32_rtt:l.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(l.hasAudio){let f={uint32_audio_codec_bitrate:l.audio.bytesReceived,uint32_audio_total_bitrate:l.audio.bytesReceived,uint32_audio_level:l.audio.audioLevel*1e8,uint32_audio_energy:l.audio.totalAudioEnergy*1e6,uint32_audio_receive:l.audio.packetsReceived,uint32_audio_origin_lost:l.audio.packetsLost};m.msg_audio_status=f}if(l.hasVideo){let f=t.get(`${l.userId}_${Mn}`),I=f?f.duration:0,b={uint32_video_stream_type:l.isSmallSubscribed?3:2,uint32_video_receive_fps:l.video.framesReceived,uint32_video_width:l.video.frameWidth,uint32_video_height:l.video.frameHeight,uint32_video_codec_bitrate:l.video.bytesReceived,uint32_video_receive:l.video.packetsReceived,uint32_video_origin_lost:l.video.packetsLost,uint32_video_block_time:I,uint32_video_dec_fps:l.video.framesDecoded};m.msg_video_status.push(b)}if(l.hasAuxiliary){let f=t.get(`${l.userId}_${Ln}`),I=f?f.duration:0,b={uint32_video_stream_type:7,uint32_video_receive_fps:l.auxiliary.framesReceived,uint32_video_width:l.auxiliary.frameWidth,uint32_video_height:l.auxiliary.frameHeight,uint32_video_codec_bitrate:l.auxiliary.bytesReceived,uint32_video_receive:l.auxiliary.packetsReceived+l.auxiliary.packetsLost,uint32_video_origin_lost:l.auxiliary.packetsLost,uint32_video_block_time:I,uint32_video_dec_fps:l.auxiliary.framesDecoded};m.msg_video_status.push(b)}e.msg_down_stream_info.push(m)});let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let l=o.msg_up_stream_info.msg_audio_status,m=e.msg_up_stream_info.msg_audio_status;if(l.uint32_audio_codec_bitrate===0)m.uint32_audio_codec_bitrate=0;else{let f=this.getDifferenceValue(l.uint32_audio_codec_bitrate,m.uint32_audio_codec_bitrate);m.uint32_audio_codec_bitrate=Math.round(f*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_audio_codec_bitrate}}let n=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(l=>{let m=n.find(ie=>ie.uint32_video_stream_type===l.uint32_video_stream_type);if(!m||m.uint32_video_codec_bitrate===0){l.uint32_video_codec_bitrate=0,l.uint32_video_enc_fps=0,l.uint32_video_codec_fps=0;return}let f=0,I=0,b=0;m&&l.uint32_video_codec_bitrate>=m.uint32_video_codec_bitrate&&(f=m.uint32_video_codec_bitrate,I=m.uint32_video_enc_fps,b=m.uint32_video_codec_fps);let k=this.getDifferenceValue(f,l.uint32_video_codec_bitrate);l.uint32_video_codec_bitrate=Math.round(k*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=l.uint32_video_codec_bitrate,l.uint32_video_enc_fps=Math.round(this.getDifferenceValue(I,l.uint32_video_enc_fps)/s),l.uint32_video_codec_fps=Math.round(this.getDifferenceValue(b,l.uint32_video_codec_fps)/s),Rt&&at()===115&&m.uint32_video_width===0&&m.uint32_video_height===0&&m.uint32_video_codec_fps===0&&(l.uint32_video_codec_fps=l.uint32_video_enc_fps),T(m.uint32_key_frame_count)||(l.uint32_key_frame_count=Math.round(this.getDifferenceValue(m.uint32_key_frame_count,l.uint32_key_frame_count))),T(m.uint32_nack_count)||(l.uint32_nack_count=Math.round(this.getDifferenceValue(m.uint32_nack_count,l.uint32_nack_count))),T(m.uint32_pli_count)||(l.uint32_pli_count=Math.round(this.getDifferenceValue(m.uint32_pli_count,l.uint32_pli_count))),T(m.uint32_video_arq_packets)||(l.uint32_video_arq_packets=Math.round(this.getDifferenceValue(m.uint32_video_arq_packets,l.uint32_video_arq_packets))),T(m.uint32_encode_cost)||(l.uint32_encode_cost=Math.round(this.getDifferenceValue(m.uint32_encode_cost,l.uint32_encode_cost)/s)),T(m.uint32_send_packet_cost)||(l.uint32_send_packet_cost=Math.round(this.getDifferenceValue(m.uint32_send_packet_cost,l.uint32_send_packet_cost)/s))});let c=e.msg_down_stream_info,u=o.msg_down_stream_info;return c.forEach(l=>{let m=u.find(f=>f.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid);if(!!m){if(!Pt(l.msg_audio_status)&&!Pt(m.msg_audio_status)){let f=l.msg_audio_status,I=m.msg_audio_status;f.uint32_audio_origin_lost=this.getDifferenceValue(I.uint32_audio_origin_lost,f.uint32_audio_origin_lost),f.uint32_audio_receive=this.getDifferenceValue(I.uint32_audio_receive,f.uint32_audio_receive),f.uint32_audio_receive+=f.uint32_audio_origin_lost;let b=this.getDifferenceValue(I.uint32_audio_codec_bitrate,f.uint32_audio_codec_bitrate);f.uint32_audio_codec_bitrate=Math.round(b*8/s),f.uint32_audio_total_bitrate=Math.round(b*8/s)}else l.msg_audio_status={};if(l.msg_video_status&&m.msg_video_status){let f=m.msg_video_status;l.msg_video_status=l.msg_video_status.filter(b=>f.find(k=>k.uint32_video_stream_type===b.uint32_video_stream_type)),l.msg_video_status.forEach(b=>{let k=f.find(il=>il.uint32_video_stream_type===b.uint32_video_stream_type),ie=k.uint32_video_receive,fe=k.uint32_video_origin_lost,ui=k.uint32_video_codec_bitrate,li=k.uint32_video_receive_fps,Ce=k.uint32_video_dec_fps;b.uint32_video_origin_lost=this.getDifferenceValue(fe,b.uint32_video_origin_lost),b.uint32_video_receive=this.getDifferenceValue(ie,b.uint32_video_receive)+b.uint32_video_origin_lost;let hi=this.getDifferenceValue(ui,b.uint32_video_codec_bitrate);b.uint32_video_codec_bitrate=Math.round(hi*8/s);let tl=this.getDifferenceValue(li,b.uint32_video_receive_fps);b.uint32_video_receive_fps=Math.round(tl/s),b.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Ce,b.uint32_video_dec_fps)/s)})}}}),e}getStatsReport(s){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var ku=Ne(Me());var pc=class extends ku.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"_uplinkRTT",0);d(this,"_uplinkLoss",0);d(this,"_downlinkRTT",0);d(this,"_downlinkLoss",0);d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=A.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this._uplinkRTT}, loss: ${this._uplinkLoss}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(B.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(ce.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,u;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=(u=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:u.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/o*100),this._uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===te.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:u,totalPacketsLost:l,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m});continue}let f=0,I=this._downlinkPrevStatMap.get(c),b=l-I.totalPacketsLost,k=m-I.totalPacketsReceived;b<=0||k<0?f=0:f=Math.round(b/(b+k)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:u,loss:f,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=o,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Ai())return t;let s=e.getReceivers();try{for(let o=0;o<s.length;o++)(yield s[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&Q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===h.AUDIO||c.mediaType===h.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state===Ve.DISCONNECTED?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===Ve.CONNECTED&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===te.DISCONNECTED||e.connectionState===te.FAILED||e.connectionState===te.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=Z.run(dt,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];E.emit(_.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(pc.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(Z.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:o,audioDelay:n})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}},Mi=pc;d(Mi,"EVENT_NETWORK_QUALITY","0");var Ht=new WeakMap;function fr({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=ht({retryFunction:n.value,settings:r,onError({error:c,retry:u,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var f;(f=Ht.get(s))!=null&&f.has(o)?u():l(c)},l,m)},onRetrying:(c,u)=>{var l;j(e)&&e(c,u),(l=Ht.get(s))!=null&&l.has(o)&&(Ht.get(s).get(o).stopRetry=u)},onRetryFailed:t});return n.value=function(...c){let u=Ht.get(s);return u?u.set(o,{args:c}):Ht.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=Ht.get(s))==null?void 0:l.delete(o)})},n}}function Cs({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var c,u;if((c=Ht.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=Ht.get(t).get(r),f=!0;if(e){for(let I of m)if(!a.find(b=>b===I)){f=!1;break}}f&&(i&&i.apply(this,a),l&&l(),(u=Ht.get(t))==null||u.delete(r))}return n.apply(this,a)},o}}function Cm({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return Qr(t)?t.catch(s=>A.error(`${r.name}() error observed ${s}`)):t}catch(t){A.error(`${r.name}() error observed ${t}`)}}}var qo=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._apiSuccessRateMap=new Map;this._eventMap=new Map;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=A.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&j(this[e])&&(this[e]=Cm({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=Z.run(dt,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return`${this._keyPrefix}_${this._room.userId}`}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ie,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:Jt[co()],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,this._apiSuccessRateMap.clear(),Br().then(i=>{this._basicInfo.string_os_version=Rn(),i&&(this._basicInfo.string_device_name=i.model)})}addEvent(i,e){return this._eventMap.set(i,e),E.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(_.JOIN_START,this.handleJoinStart).addEvent(_.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(_.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(_.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(_.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(_.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(_.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(_.JOIN_FAILED,this.handleJoinFailed).addEvent(_.LEAVE_START,this.handleLeaveStart).addEvent(_.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(_.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(_.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(_.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(_.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(_.PUBLISH_START,this.handlePublishStart).addEvent(_.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(_.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(_.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(_.PLAY_TRACK_START,this.handlePlayStart).addEvent(_.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(_.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!Yt(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(_.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(_.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(_.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(_.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(_.API_SUCCESS_RATE,this.handleAPISuccessRate).addEvent(_.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(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((i,e)=>E.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Z.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:s,dns:o,tcp:n,tls:a,request:c,response:u}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=u}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&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:i,error:e}){this.hitTest(i)&&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 C?Number(e.getExtraCode()||e.getCode()):g.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.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(i){this.hitTest(i.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=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(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(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||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(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.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(i){this.hitTest(i.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(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,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:M(N({},Nm),{msg_user_info:new Ns({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new Ns({userId:o,tinyId:n,role:a==="anchor"?20:21}),u=Date.now(),l=`${o}_${t}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=u),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:u}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:u})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:u})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(s);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!Yt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!Yt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),o)){let{statsToReport:a,playStreamTime:c,subscribedTime:u}=o;a.uint32_video_render_first===0&&c-u<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let n=this._pathAuxiliaryMap.get(e);if(n&&o){let{statsToReport:a,playStreamTime:c,subscribedTime:u}=o;a.uint32_video_render_first===0&&c-u<=100&&(a.uint32_video_render_first=t-n.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,u,l,m;o&&(u=o,l=1),n&&(c=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:u,audioDelayCount:m,videoDelayCount:l})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_up_stream_info:e,msg_down_stream_info:t}=i.report;if(e.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:o,uint32_video_width:n,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=o,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:s}=e.msg_audio_status;Math.floor(s/Xe*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Xe,this._localStreamStat.audioLevelCount++)}t.forEach(s=>{let{msg_user_info:o,msg_audio_status:n,msg_video_status:a}=s,c=o.str_identifier,u=this._room.remotePublishedUserMap.get(c);if(a.forEach(l=>{let m=l.uint32_video_stream_type===2,f=l.uint32_video_stream_type===7,I=`${c}_${m?"main":"auxiliary"}`,b=this._remoteStreamStatMap.get(I);if(!!b&&(m&&(u==null?void 0:u.remoteVideoTrack.isSubscribed)||f&&(u==null?void 0:u.remoteAuxiliaryTrack))){b.totalVideoFPS+=l.uint32_video_receive_fps,b.totalVideoBitrate+=l.uint32_video_codec_bitrate,b.videoCount++,b.statsToReport.uint32_video_width===0&&(b.statsToReport.uint32_video_width=l.uint32_video_width),b.statsToReport.uint32_video_height===0&&(b.statsToReport.uint32_video_height=l.uint32_video_height);let k=m?u.remoteVideoTrack:u.remoteAuxiliaryTrack;k.stat.jitterBufferDelay&&(b.videoJitterBufferDelay=k.stat.jitterBufferDelay),k.stat.framesReceived&&(b.statsToReport.uint32_video_consume_render_rate=Math.floor(k.stat.framesDecoded/k.stat.framesReceived*ks(10,6)))}}),n){let l=`${c}_${"main"}`,m=this._remoteStreamStatMap.get(l);this._remoteStreamStatMap.has(l)&&m&&(u==null?void 0:u.remoteAudioTrack.isSubscribed)&&(m.totalAudioBitrate+=n.uint32_audio_codec_bitrate,m.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(n.uint32_audio_level/Xe*100)>0&&(m.totalAudioLevel+=n.uint32_audio_level/Xe,m.audioLevelCount++))}})}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.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()),i.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:i,error:e}){let s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof C?e.getExtraCode()||e.getCode():g.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate({room:i,apiName:e,error:t,cost:s}){if(!this.hitTest(i))return;let o=Mu[e],n={uint32_function_request_type:o,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(t){let c=t.extraCode||t.code||g.UNKNOWN;q.logFailedEvent({eventType:e,code:c,userId:this._room.userId,error:t});let u={int32_error_code:c,error_count:1};n.msg_error_code.push(u)}else Q(s)&&(q.logSuccessEvent({eventType:e,userId:this._room.userId}),n.uint32_avg_value=s,n.uint32_max_value=s,n.uint32_success_count=1);let a=this._apiSuccessRateMap.get(o);a?(a.uint32_success_count+n.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+n.uint32_avg_value)/(a.uint32_success_count+n.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,n.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+n.uint32_success_count,n.msg_error_code.forEach(c=>{let u=a.msg_error_code.find(l=>l.int32_error_code===c.int32_error_code);u?u.error_count+=1:a.msg_error_code.push(c)})):this._apiSuccessRateMap.set(o,n)}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ji)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Yi)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Hr)>=0}hitTest(i){return i===this._room}checkStorage(){return p(this,null,function*(){try{let i=rr.getItem(this._storageKey);i&&(yield this.upload(i),rr.deleteItem(this._storageKey))}catch(i){this._log.warn(i)}})}setStorage(){this.prepareReport();let i=this.getReportData();i.msg_path_enter_room.uint64_start_time!==0&&rr.setItem(this._storageKey,i)}prepareReport(){if(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 i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<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((i,e)=>{let{userId:t}=i,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:l,count:m,audioDelayCount:f,videoDelayCount:I,totalAudioDelay:b,totalVideoDelay:k}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/m),f&&b&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(b/f),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),I&&k&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(k/I))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Li);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:u}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(u,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Li&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Li)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>Li&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Li)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Li&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Li)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Ns({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:zr(this._signalInfo.relayIp),uint32_client_ip:zr(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*2147483648),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:zr(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){try{this.prepareReport();let i=this.getReportData();this.upload(i),rr.deleteItem(this._storageKey),this.initData()}catch(i){this._log.warn(i)}}upload(i){if(Ye||i.msg_path_enter_room.uint64_start_time===0||[zs,Nn,yn].findIndex(o=>o===location.host)>=0)return;let e=Number(this._room.sdkAppId),t=Si(e,fi.KEY_POINT),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(t,JSON.stringify(i))),s||qt({url:t,body:JSON.stringify(i)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}};y([fr({settings:{timeout:500,retries:3}})],qo.prototype,"upload",1);var Li=5e3,Nm={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},Ns=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Mu=(R=>(R[R.enterRoom=50001]="enterRoom",R[R.exitRoom=50002]="exitRoom",R[R.switchRole=50003]="switchRole",R[R.destroy=50004]="destroy",R[R.startLocalAudio=50005]="startLocalAudio",R[R.updateLocalAudio=50006]="updateLocalAudio",R[R.stopLocalAudio=50007]="stopLocalAudio",R[R.startLocalVideo=50008]="startLocalVideo",R[R.updateLocalVideo=50009]="updateLocalVideo",R[R.stopLocalVideo=50010]="stopLocalVideo",R[R.startScreenShare=50011]="startScreenShare",R[R.updateScreenShare=50012]="updateScreenShare",R[R.stopScreenShare=50013]="stopScreenShare",R[R.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",R[R.startRemoteVideo=50015]="startRemoteVideo",R[R.updateRemoteVideo=50016]="updateRemoteVideo",R[R.stopRemoteVideo=50017]="stopRemoteVideo",R[R.muteRemoteAudio=50018]="muteRemoteAudio",R[R.setRemoteAudioVolume=50019]="setRemoteAudioVolume",R[R.startMixTranscode=50020]="startMixTranscode",R[R.stopMixTranscode=50021]="stopMixTranscode",R[R.startPublishCDNStream=50022]="startPublishCDNStream",R[R.stopPublishCDNStream=50023]="stopPublishCDNStream",R[R.PeerConnectionConnect=50024]="PeerConnectionConnect",R[R.PeerConnectionReconnect=50025]="PeerConnectionReconnect",R[R.WebsocketConnect=50026]="WebsocketConnect",R[R.WebsocketReconnect=50027]="WebsocketReconnect",R[R.schedule=50028]="schedule",R[R.SPCConnect=50029]="SPCConnect",R[R.SPCReconnect=50030]="SPCReconnect",R[R.videoCtxGl=50031]="videoCtxGl",R[R.videoCtxGlRecover=50032]="videoCtxGlRecover",R[R.videoCtx2d=50033]="videoCtx2d",R[R["CDNStreaming.startPlugin"]=50034]="CDNStreaming.startPlugin",R[R["CDNStreaming.updatePlugin"]=50035]="CDNStreaming.updatePlugin",R[R["CDNStreaming.stopPlugin"]=50036]="CDNStreaming.stopPlugin",R[R["AIDenoiser.startPlugin"]=50037]="AIDenoiser.startPlugin",R[R["AIDenoiser.updatePlugin"]=50038]="AIDenoiser.updatePlugin",R[R["AIDenoiser.stopPlugin"]=50039]="AIDenoiser.stopPlugin",R[R["AudioMixer.startPlugin"]=50040]="AudioMixer.startPlugin",R[R["AudioMixer.updatePlugin"]=50041]="AudioMixer.updatePlugin",R[R["AudioMixer.stopPlugin"]=50042]="AudioMixer.stopPlugin",R))(Mu||{}),Lu=qo;var _c=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=$())}stop(){this._endTime===0&&(this._endTime=$())}getDuration(){return this._endTime===0?$()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Er=_c;var fc=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(_.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(_.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(_.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,h.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!o||(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let n=new Er,a=this._durationMap.get(o);a?this.isRecording(a.audio)||a.audio.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[n],video:[]})}else this.stopDurationItem(o,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let n=new Er,a=this._durationMap.get(o);a?this.isRecording(a.video)||a.video.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[],video:[n]})}else this.stopDurationItem(o,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,o=new Er,n=this._durationMap.get(s);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(o=>o.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,o)=>s+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Pu=fc;var Ec=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new Map);d(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(_.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(_.PLAY_TRACK_START,this.onPlayTrackStart).set(_.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDataFreeze({key:o,userId:s,type:e})}).set(_.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}}).set(_.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!Yt(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(_.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,o=this._dataFreezeMap.get(s),n=new Er;o?o.durationItemList.push(n):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:o,muteState:n}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let o=s.durationItemList[s.durationItemList.length-1];o.stop();let n=o.getDuration();n>oo?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return p(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=$();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=$();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!Yt(i)||!this.hitTest(i.room)||i.kind!==h.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<oo&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=$(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},xu=Ec;var Tc=null,gc=!0;function ci(r){re(r)&&r!==gc&&(gc=r,A.info(`setIsNeedToSchedule ${r}`))}E.on("28",()=>ci(!0));E.on("63",()=>ci(!0));E.on("84",()=>ci(!0));E.on("201",r=>{r.state==="RECONNECTING"&&ci(!0)});E.on("202",r=>{r.state==="RECONNECTING"&&ci(!0)});function ym(r,i,e){let t=performance.getEntriesByType("resource"),s=zo(r,h.MAIN),o=zo(r,h.BACKUP),n={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of t)if(a.startTime>=e&&(a.name===s||a.name===o)&&a.transferSize>0){let c=a.name===s?h.MAIN:h.BACKUP,u=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=Math.round(a.domainLookupEnd-a.domainLookupStart),f=Math.round(a.requestStart-a.secureConnectionStart),I=Math.round(a.secureConnectionStart-a.connectStart),b=Math.round(a.responseStart-a.requestStart),k=Math.round(a.responseEnd-a.responseStart),ie=[l,m,f,I,b,k];q.uploadEvent({log:`stat-schedule-net:${u}(${ie.join("->")}) ${c}`,userId:i}),n=M(N({},n),{totalCost:u,local:l,dns:m,tcp:I,tls:f,request:b,response:k});break}return n}function Vu(a){return p(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:o,frameWorkType:n}){if(!gc&&Tc)return{isCached:!0,result:Tc};let c={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(r)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(e)),u.append("groupId",String(t)),u.append("sdkVersion",o),u.append("userSig",String(s)),u.append("frameWorkType",String(n));let l=$(),m=yield Om(u,c,i);m.config&&(m.config.loggerDomain&&_i(m.config.loggerDomain),re(m.config.scheduleCache)&&ci(!m.config.scheduleCache)),c.delta=$()-l;let f=ym(Number(i),r,l);return Tc=m,{isCached:!1,result:m,detailCost:f}}catch(u){let l=de(u)?u[0]:u,m=Q(l.code)?l.code:0,f=`schedule failed${l.message?`: ${l.message}`:""}`,I=new C({code:g.SCHEDULE_FAILED,extraCode:m,message:D({key:O.JOIN_ROOM_FAILED,data:{error:f,code:m}})});throw A.error(I),I}})}var Xo={main:"",backup:""};function Sc(r){de(r)?(Xo.main=r[0],Xo.backup=r[1]):Xo.main=r}function zo(r,i=h.MAIN){let e;return ao(r)?e=i===h.MAIN?qi.MAIN_OVERSEA:qi.BACKUP_OVERSEA:e=i===h.MAIN?qi.MAIN:qi.BACKUP,`https://${Xo[i]||e}/api/v1/config`}function bm(r,i,e){return new Promise((t,s)=>{qt({url:r,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var wu=(r,i)=>ht({retryFunction:bm,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function Om(r,i,e){return new Promise((t,s)=>{let o=null;Fn([wu(n=>i.count[0]=n+1,({error:n,retry:a})=>{i.msg[0]=n.message,o||a()})(zo(e,h.MAIN),r,{get timeout(){return er(2+i.count[0])*1e3}}),wu(n=>i.count[1]=n+1,({error:n,retry:a})=>{i.msg[1]=n.message,o||a()})(zo(e,h.BACKUP),r,{get timeout(){return er(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var Uu=Ne(Me(),1);var Dm=[-1,-1,-1,1,1,-1,1,1],vm=[0,0,0,1,1,0,1,1],Be=class extends L{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"image");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"_canvas",null);this.context.once("disconnect",()=>{this.state!=="closed"&&this.close()}),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height;let s=e._gl;if(!s){if(e.ctx2d&&t.create2d){let o=document.createElement("canvas"),n=typeof o.transferControlToOffscreen=="function"?o.transferControlToOffscreen():o;n.width=this.width,n.height=this.height,this.ctx2d=n.getContext("2d"),this.image=n,this._canvas=n}return}try{t.createTexture!==!1&&(this.texture=s.createTexture()),this.texCoordBuffer=this.createBuffer(vm),this.positionBuffer=this.createBuffer(Dm),this.useTexture(()=>{s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE)}),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(()=>{this.useTexture(()=>{s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)})})),t.useDefaultProgram&&(this.program=this.context.defaultProgam),t.vertexShaderSource&&t.fragmentShaderSource&&(this.vertexShader=e.createShader(s.VERTEX_SHADER,t.vertexShaderSource),this.fragmentShader=e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource),this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(`${this.name} init failed`,o)}}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){if(this.context._gl&&this.render(e)||this.context.ctx2d&&this.render2d(e))this.totalFrames++;else return!1;return!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var t,s;(t=this.output)==null||t.removeInput(this),delete this.output,(s=this.input)==null||s.disconnect();let e=this.context._gl;e&&(e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)),this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(e,t){this.texture&&this.context.useTexture(this.texture,e,t)}useInputTexture(e,t){this.context.useTexture(this.input.texture,e,t)}useProgram(){this.context._gl.useProgram(this.program)}useBufferFrame(e){let t=this.context._gl;t.bindFramebuffer(t.FRAMEBUFFER,this.fbo),e(),t.bindFramebuffer(t.FRAMEBUFFER,null)}createBuffer(e){let t=this.context._gl,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context._gl,s=this.texCoordBuffer;t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context._gl,s=this.positionBuffer;t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context._gl;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(e){let t=this.context._gl;for(let s in e){let o=t.getAttribLocation(this.program,s);t.bindBuffer(t.ARRAY_BUFFER,e[s]),t.enableVertexAttribArray(o),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)}}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo&&this.useTexture(s=>s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)),this.output&&this.output.matchInputSize&&this.output.resize(e,t))}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var u;let{totalFrames:e,x:t,y:s,width:o,height:n}=this,a=Date.now(),c=(e-this.lastInfo.totalFrames)/((a-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:a,fps:c},N({parent:(u=this.input)==null?void 0:u.getInfo()},this.lastInfo)}};y([ee(L.INIT,"connected")],Be.prototype,"connect",1),y([ee("connected",L.INIT,{ignoreError:!0})],Be.prototype,"disconnect",1),y([ee([],"closed")],Be.prototype,"close",1);var km=[0,1,0,0,1,1,1,0],Ic=class extends Be{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);e._gl?this.setTexBuffer(km):e.ctx2d&&(this.ctx2d=e.ctx2d)}start(e){this._intervalId=Z.run("intervalInWorker",()=>{e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++);let t=this.context._gl;t&&t.getError()!==t.NO_ERROR&&this.context.destroy(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${t.getError()}`)},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useInputTexture(s=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),s.drawArrays(s.TRIANGLE_STRIP,0,4)}),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}},ys=class extends Ic{constructor(e,t){super(e,t);d(this,"_videoTrack");[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let s=o=>{let n=()=>this._videoTrack.removeEventListener(o,a),a=()=>{n(),this.context.destroy(`video track ${o}`)};this.once("closed",n),this._videoTrack.addEventListener(o,a)};e._gl&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}close(){super.close(),this._videoTrack.stop()}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}};var Zo=class extends ys{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;A.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(A.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var bs=class extends Be{constructor(e,t){super(e,{name:"imageSource"});this.image=t;d(this,"_image");d(this,"_totalFrames",0)}_render(e,t){let{width:s,height:o}=this;if(this.image instanceof HTMLVideoElement){if(j(this.image.getVideoPlaybackQuality)&&!Sn){let a=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===a)return!1;this._totalFrames=a,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:s,videoHeight:o}=this.image)}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:o}=this.image,this.image!==this._image)this._image=this.image;else if(s===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:o}=this.image,this._image=this.image);return this.width===s&&this.height===o&&this.totalFrames?t&&this.useTexture(n=>{n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.image)}):(t&&this.useTexture(n=>{n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,this.image)}),this.resize(s,o)),!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},en=class extends bs{constructor(e,t){super(e,document.createElement("video"));this._videoTrack=t;d(this,"_mediaStream");this.name="videoTrackSource",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var t,s;this._videoTrack!==e&&((t=this._mediaStream)==null||t.removeTrack(this._videoTrack),this._videoTrack=e,(s=this._mediaStream)==null||s.addTrack(this._videoTrack),this.image.play())}close(){super.close(),delete this._mediaStream,this.image.srcObject=null}};var Mm=`
  38. // \u9876\u70B9\u7740\u8272\u5668
  39. attribute vec4 a_position;
  40. attribute vec2 a_texCoord;
  41. varying vec2 v_texCoord;
  42. void main() {
  43. gl_Position = a_position;
  44. v_texCoord = a_texCoord;
  45. }
  46. `,Lm=`
  47. // \u7247\u5143\u7740\u8272\u5668
  48. precision mediump float;
  49. varying vec2 v_texCoord;
  50. uniform sampler2D u_texture;
  51. void main() {
  52. gl_FragColor = texture2D(u_texture, v_texCoord);
  53. } `,Pi=class extends L{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"_gl");d(this,"ctx2d");d(this,"defaultProgam");d(this,"log");d(this,"hasAlpha",!1);d(this,"glFaild",!1);d(this,"name");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}create(e){if(this.glFaild=!1,this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),e.use2d){this.ctx2d=this._canvas.getContext("2d",{alpha:e.alpha}),this.log.info("video context created use 2d");return}let t=this._canvas.getContext("webgl",{alpha:e.alpha});if(t){this._gl=t;try{let s=this.createShader(t.VERTEX_SHADER,Mm),o=this.createShader(t.FRAGMENT_SHADER,Lm);this.defaultProgam=this.createProgram(s,o),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy("webglcontextlost")}),this.log.info("video context created use webgl")}catch(s){return this.log.warn("video context create faild use webgl"),s}}else this.ctx2d=this._canvas.getContext("2d"),this.ctx2d&&this.log.info("video context created downgrade to 2d");!this.ctx2d&&!this._gl&&delete this._canvas}get available(){return!!this._canvas}createVideoTrackSource(e){return new en(this,e)}createVideoTrackDestination(e){return new ys(this,e)}createVideoImageSource(e){return new bs(this,e)}set width(e){var t;(t=this._gl)==null||t.viewport(0,0,e,this.height),this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){var t;(t=this._gl)==null||t.viewport(0,0,this.width,e),this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){var s;(s=this._gl)==null||s.viewport(0,0,e,t),this._canvas&&(this._canvas.width=e,this._canvas.height=t)}disconnect(){this.emit("disconnect")}destroy(e,t){var s;return this.disconnect(),this.log.info(`video context destroy ${e?`:${e}`:""}`),(s=this._gl)==null||s.deleteProgram(this.defaultProgam),delete this._gl,delete this.ctx2d,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),[e,t]}createShader(e,t){let s=this._gl,o=s.createShader(e);return s.shaderSource(o,t),s.compileShader(o),o}createProgram(e,t){let s=this._gl,o=s.createProgram();return s.attachShader(o,e),s.attachShader(o,t),s.linkProgram(o),o}useTexture(e,t,s){let o=this._gl;o.activeTexture(o.TEXTURE0+(s||0)),o.bindTexture(o.TEXTURE_2D,e),t(o),o.bindTexture(o.TEXTURE_2D,null)}};y([ee(L.INIT,"created")],Pi.prototype,"create",1),y([ee("created",L.INIT,{ignoreError:!0,success(r){r[0]&&(this.glFaild=!0,this.emit("unavailable",...r)),this.removeAllListeners()}})],Pi.prototype,"destroy",1);var Pm=[1,0,1,1,0,0,0,1],tn=class extends Be{constructor(i){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),i._gl)try{this.setTexBuffer(Pm)}catch(e){i.destroy("mirror set texCoords faild",e)}else this.ctx2d&&setTimeout(e=>{e.scale(-1,1),e.translate(-this.width,0)},0,this.ctx2d)}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(()=>{this.useInputTexture(t=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),t.drawArrays(t.TRIANGLE_STRIP,0,4)})}),!0):!1}};var Ac=class{constructor(i,e){this.node=i;this.layout=e;d(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}},rn=class extends Be{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0});d(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let s=new Ac(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(s.width,s.height),this.context._gl&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context._gl;return!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t?(this.useProgram(),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),this.setAttributes({a_texCoord:this.texCoordBuffer}),this.useBufferFrame(()=>{for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&n.node.useTexture(a=>{this.setAttributes({a_position:n.positionBuffer}),a.drawArrays(a.TRIANGLE_STRIP,0,4)})}}),!0):!1}render2d(e){if(!this.inputs.reduce((s,o)=>(!o||!o.node.requestFrame(e))&&s,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:o,height:n}=this,a=Date.now(),c=(e-this.lastInfo.totalFrames)/((a-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:a,fps:c},N({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context._gl))try{this.context._gl.deleteBuffer(e.positionBuffer)}catch(s){}})}};var sn=class extends Uu.EventEmitter{constructor({room:e}){super();d(this,"videoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"cameraTrack");d(this,"cameraNode");d(this,"waterMarkNode");d(this,"mirrorNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"_isMixScreen",!1);d(this,"_hasWaterMark",!1);d(this,"_log");d(this,"_checkId",0);d(this,"_room");d(this,"_use2d",!0);d(this,"_waterMarkOption");d(this,"_isOpenVirtualBackground",!1);d(this,"_virtualBackgroundTrack");d(this,"virtualBackgroundInstance");this._room=e,this._log=A.createLogger({id:"vm",userId:e.userId,sdkAppId:e.sdkAppId}),this.videoContext=new Pi({frameRate:15,logger:this._log,name:"m"}),this.videoContext.on("unavailable",(t,s)=>{this.emit("error",{reason:t,error:s}),this._log.warn("video context unavailable",t,s,`glFaild:${this.videoContext.glFaild}`),E.emit("262",{room:this._room,apiName:"videoCtxGl",error:s||new Error(t)}),this.update()}),this.smallVideoContext=new Pi({frameRate:15,logger:this._log,name:"s"}),this.enablePrintDetail()}get renderMode(){return this._use2d?"2d":"webgl"}set renderMode(e){let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.videoContext&&(this.clear(),this.videoContext.destroy(),this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d}),this.update()))}enablePrintDetail(e=2e3){this._checkId=Z.run(gi,()=>{this.destination&&this._log.debug(this.destination.getInfo())},{delay:e})}destroy(){this.videoContext.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get active(){return(Ur&&An||this._isMixScreen||this._isMirror||this._hasWaterMark)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){E.emit("262",{room:this._room,apiName:e,error:t})}checkOrCreateVideoContext(){if(this.videoContext.available)if(!this.videoContext.hasAlpha&&this._hasWaterMark)this.clear(),this.videoContext.destroy();else return!0;else this.videoContext.glFaild&&(this.clear(),this._use2d=!0);let e=this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d});return this.videoContext._gl?this.sendCreateResult():(this._use2d||(this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)),this.sendCreateResult("videoCtx2d",this.videoContext.ctx2d?void 0:new Error("create 2d context failed"))),this.videoContext.available}get smallTrack(){return this.smallDestination.videoTrack}get hasSmall(){return!!this.smallTrackSource||!!this.smallImageSource}get initialTrack(){var e;return this._isOpenVirtualBackground&&this._virtualBackgroundTrack?this._virtualBackgroundTrack:(e=this.cameraTrack)==null?void 0:e.mediaTrack}_setMainOutput(e){let t=this.cameraTrack,{small:s,settings:o}=t;return s&&(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1,use2d:!0}),this.smallDestination=new Zo(this.smallVideoContext,s)),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),this.smallTrackSource.width=o.width,this.smallTrackSource.height=o.height,this.smallTrackSource.connect(this.smallDestination)))),t.setOutputMediaStreamTrack(e?this.destination.videoTrack:this.initialTrack)}update(){return p(this,null,function*(){var s,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(this.active){let{settings:n,profile:a}=this.cameraTrack;this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(n.width,n.height)),this.videoContext.frameRate=a.frameRate}else return this.cameraNode&&this.clear(),this._setMainOutput();let e=this.cameraNode;return e.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new tn(this.videoContext)),e=e.connect(this.mirrorNode),e.disconnect(),this._log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new rn(this.videoContext),e.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),e=this.mixNode,this._log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),e.connect(this.destination),this._setMainOutput(this.videoContext._canvas)})}changeInput(e,t){if(this._log.info("change input"),e instanceof xe)return this.setScreenTrack(e);if(e instanceof ke)return this.setCameraTrack(e);if(e instanceof ft)return e.setOutputMediaStreamTrack(e.mediaTrack)}removeInput(e){var t;e instanceof xe?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ke?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ft}setCameraTrack(e){return p(this,null,function*(){return this.cameraTrack=e,this._isOpenVirtualBackground&&(yield this.updateAr()),this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}loadImage(e){return new Promise((t,s)=>{let o=new Image;o.crossOrigin="anonymous",o.src=e,o.onload=()=>t(o),o.onerror=s})}setWatermark(e){return p(this,null,function*(){let t=yield this.loadImage(e.imageUrl),{x:s=0,y:o=0,width:n=t.width,height:a=t.height}=e;this._hasWaterMark=!0,this._waterMarkOption={x:s,y:o,width:n,height:a,image:t},this._log.info("start watermark",JSON.stringify({x:s,y:o,width:n,height:a})),this.update()})}stopWatermark(){var e;!this._hasWaterMark||(this._hasWaterMark=!1,this._log.info("stop watermark"),(e=this.waterMarkNode)==null||e.close(),delete this.waterMarkNode,this.update())}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update()}get mirror(){return this._isMirror}enableAr(e){return p(this,null,function*(){this.virtualBackgroundInstance=e,this._isOpenVirtualBackground=!0,this.virtualBackgroundInstance.ar.enable(this.cameraTrack.mediaTrack.clone()),this.virtualBackgroundInstance.ar.listen("output",this.handleArOutput.bind(this))})}handleArOutput(e){this._virtualBackgroundTrack=e,this.update()}updateAr(){return p(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;!this._isOpenVirtualBackground||(this._isOpenVirtualBackground=!1,(e=this._virtualBackgroundTrack)==null||e.stop(),this._virtualBackgroundTrack=null,this.update())}clear(){this.videoContext.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}};var xm=0;var on=class extends L{constructor(e){super("room");this.seq=++xm;this.role="anchor";this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=A.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this._isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,re(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),re(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),re(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new Lu({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Pu({room:this}),this.badCaseDetector=new xu({room:this}),this.audioManager=new Co({room:this}),this.videoManager=new sn({room:this})}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}getLogger(){return this._log}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return p(this,null,function*(){return this.publish(e)})}removeTrack(e){return p(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return p(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Y(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Fe(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Sc([a,a]),_i(`https://${a}`)):(o&&_i(o),n&&Sc(n))}}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return p(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return p(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=o.stat}),t})}checkDestroy(){if(this._isDestroyed)throw new C({code:g.INVALID_OPERATION,message:D({key:O.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(me.INVALID_DESTROY),new C({code:g.INVALID_OPERATION,message:D({key:O.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,E.emit(_.ROOM_DESTROY,{room:this})}schedule(e,t,s){return p(this,null,function*(){var n,a;let o=$();try{let{isCached:c,result:u,detailCost:l}=yield Vu({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:s,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=c,this._log.info(`schedule cache:${+c} ${ze(u,{keysToExclude:["username","credential"]})}`),c&&E.once(_.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),u),Q((n=u.config)==null?void 0:n.retryCount)&&Pn(u.config.retryCount),Y((a=u.config)==null?void 0:a.loggerDomain)&&_i(u.config.loggerDomain),E.emit(_.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),E.emit(_.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:$()-o})}catch(c){throw E.emit(_.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:c}),c}})}};var di=new WeakMap,gt=new WeakMap;function Os(){return function(r,i,e){let t=e.value,s=({fn:o,args:n,context:a,resolve:c,reject:u})=>{o.apply(a,n).then(c,u)};return e.value=function(...o){return new Promise((a,c)=>{if(di.has(this)){let u=di.get(this),{length:l}=u;u.push({fn:t,args:o,context:this,resolve:a,reject:c}),l===0&&s({fn:t,args:o,context:this,resolve:a,reject:c})}else di.set(this,[{fn:t,args:o,context:this,resolve:a,reject:c}]),s({fn:t,args:o,context:this,resolve:a,reject:c})}).finally(()=>{let a=di.get(this);a&&(a.shift(),a[0]&&s(N({},a[0])))})},e}}function Bu(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=di.get(this);if(n){let a=n.filter((c,u)=>{if(u===0)return!0;let l=!0;return c.args.forEach(m=>{o.find(f=>f===m)||(l=!1)}),l?(c.reject(new C({code:g.API_CALL_ABORTED,message:r})),!1):!0});di.set(this,a)}return s.apply(this,o)},t}}function $u(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c;let n=[];return(a=di.get(this))==null||a.forEach(u=>n.push(u)),(c=gt.get(this))==null||c.forEach(u=>u.forEach(l=>n.push(l))),n.forEach(u=>{u.reject(new C({code:g.API_CALL_ABORTED,message:r}))}),di.delete(this),gt.delete(this),s.apply(this,o)},t}}function Rc(r){return function(i,e,t){let s=t.value,o=a=>Q(r)?a[r]:r(...a),n=({fn:a,args:c,context:u,resolve:l,reject:m})=>{a.apply(u,c).then(l,m).finally(()=>{if(gt.has(u)&&gt.get(u).has(o(c))){let f=gt.get(u).get(o(c));f&&(f.shift(),f[0]&&n(N({},f[0])))}})};return t.value=function(...a){return new Promise((c,u)=>{if(gt.has(this))if(gt.get(this).has(o(a))){let l=gt.get(this).get(o(a));if(l){let{length:m}=l;l.push({fn:s,args:a,context:this,resolve:c,reject:u}),m===0&&n({fn:s,args:a,context:this,resolve:c,reject:u})}}else gt.get(this).set(o(a),[{fn:s,args:a,context:this,resolve:c,reject:u}]),n({fn:s,args:a,context:this,resolve:c,reject:u});else{let l=new Map;l.set(o(a),[{fn:s,args:a,context:this,resolve:c,reject:u}]),gt.set(this,l),n({fn:s,args:a,context:this,resolve:c,reject:u})}})},t}}var Ju=Ne(Me());var Cc=Ne(dc()),Fu=r=>{let i=ue(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var o;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(s){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e},Hu=(r,i)=>{var a,c;let e=ue(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:i};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],o=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(u=>({id:u.value,uri:u.uri}))),o.ext&&(t.video.extensions=o.ext.map(u=>({id:u.value,uri:u.uri})));let n={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(a=s.rtcpFb)==null||a.forEach(({payload:u,type:l,subtype:m})=>{if(u===n.payload){let f={id:l,params:[]};m&&f.params.push(m),n.rtcpFb.push(f)}}),t.audio.codecs.push(n);for(let u=0;u<o.rtp.length;u++){if(["rtx","red","ulpfec"].includes(o.rtp[u].codec))continue;let l=o.fmtp.filter(m=>m.payload===o.rtp[u].payload)[0];t.video.codecs.push({payload:o.rtp[u].payload,codec:o.rtp[u].codec,fmtp:l?l.config:"",rate:o.rtp[u].rate,rtx:((c=o.rtp[u+1])==null?void 0:c.codec)==="rtx"?o.rtp[u+1].payload:0,rtcpFb:((o==null?void 0:o.rtcpFb)||[]).filter(m=>m.payload===o.rtp[u].payload).map(({type:m,subtype:f})=>({id:m,params:f?[f]:[]}))})}return t},Gu=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ue(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Nc({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&o.media.push(s.media.find(a=>a.mid==="dc")),We(o)},Nc=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,useAllCodec:s=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(s)for(let n=0;n<i.video.codecs.length;n++)nn(o,i.video.codecs[n]);else{let n=i.video.codecs.findIndex(a=>a.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));nn(o,i.video.codecs[n])}else if(s)for(let n=0;n<e.video.codecs.length;n++)nn(o,e.video.codecs[n]);else nn(o,e.video.codecs[0]);return o.payloads=o.payloads.trim(),o},nn=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`,r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function wm(r){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);r.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function Vm(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function Um(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function Bm(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Wu=r=>{let i=Cc.default.parse(r);return i.media.forEach(e=>{var t;(e.type===h.AUDIO||e.type===h.VIDEO)&&(Vm(e),Um(e),Bm(e),wm(e)),((t=e.payloads)==null?void 0:t.includes("datachannel"))&&i.groups&&e.mid&&(i.groups[0].mids=i.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")}),Cc.default.write(i)};var St=(a=>(a.TRACK="track",a.DATA_CHANNEL_MESSAGE="data_channel_msg",a[a.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",a[a.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",a.RECONNECTED="spc-reconnected",a.RECONNECT_FAILED="spc-reconnect-failed",a.ERROR="error",a))(St||{}),ju=0,Yu=!1,$m=new Set,Fm=r=>ju>2&&!Yu&&$m.size===0&&r,Hm=1,Tr=class extends Ju.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"_clientAbility",null);d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"_waitForPCConnectedPromiseReject",null);d(this,"_isSDPLogged",!1);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${Hm++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?Fu(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return p(this,null,function*(){try{this._peerConnection=new RTCPeerConnection({offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let t=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${t}`),t==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():t==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=t=>this.emit("track",t),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=t=>{let s=new bc(t.data);this.emit("data_channel_msg",{data:s})},this._datachannel.onerror=t=>{this._log.warn("datachannel error",t)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:t}=this;!t||(this._log.debug(`dtls state: ${t.state}`),t.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():t.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),this._clientAbility=Hu(e.sdp,this._enableCustomMessage),this._clientAbility}catch(e){throw this._log.error(`initialize failed ${e}`),e}})}connect(e,t=!1){return p(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let s=$(),o={type:"answer",sdp:Gu({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min($()-s,30*1e3)})}catch(s){let o=s instanceof C&&s.code===g.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${s}`,e),this.reset(),!o&&!this.isReconnecting&&(E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return p(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(ce.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:B.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});yield this.connect(t.data.data.ability,!0),this._log.warn("reconnect() successfully"),this.stopReconnection(),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=He(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error(`reconnect() failed ${e}`),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:e}),this.reconnectionCount>=Ot()&&this._log.warn(`SDK has tried reconnect for ${Ot()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return p(this,null,function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=$();yield this.reconnect(),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min($()-e,30*1e3)})})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ce.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===te.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===te.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===te.FAILED||e.target.connectionState===te.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===te.CONNECTED||e.target.connectionState===te.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),E.emit(_.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return qe;let e=null;return!sr()||this._peerConnection.getSenders().length===0?qe:(e=this._peerConnection.getSenders()[0].transport,!Ai()||this._peerConnection.getReceivers().length===0?qe:e?e.state:qe)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(St.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(zt(s)){let o=e.get(s.localCandidateId),n=e.get(s.remoteCandidateId);o&&this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=t;let s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new C({code:g.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{E.off(_.LEAVE_SUCCESS,o,this),this.off(St.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{n();let c=new C({code:g.API_CALL_TIMEOUT,message:"connection timeout"});ju+=1,Fm(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),Yu=!0,this.emit(St.FIREWALL_RESTRICTION)),t(c)},Kr);E.on(_.LEAVE_SUCCESS,o,this),this.on(St.CONNECTION_STATE_CHANGED,s,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return p(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP({isNeedToCreateOffer:!0}),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.info(`addDownlink(${e.userId}) failed`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().filter(l=>l.direction==="inactive").slice(0,3).map(l=>(l.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(l.mid)));o.length===0&&(this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp));let n,a,c;if(o.length===3)n=this._parsedAnswer.media.find(l=>Number(l.mid)===Number(o[0])),a=this._parsedAnswer.media.find(l=>Number(l.mid)===Number(o[1])),c=this._parsedAnswer.media.find(l=>Number(l.mid)===Number(o[2]));else{n=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let l=Nc({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:ue(this._peerConnection.localDescription.sdp),useAllCodec:!0});a=JSON.parse(JSON.stringify(l)),c=JSON.parse(JSON.stringify(l)),n.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(n),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c)}n.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,n.ssrcs=[{id:e.audio,attribute:"cname",value:`${s}`},{id:e.audio,attribute:"msid",value:`${s}-${h.MAIN} ${s}-audio`}],a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,a.ssrcs=[{id:e.video,attribute:"cname",value:`${s}`},{id:e.video,attribute:"msid",value:`${s}-${h.MAIN} ${s}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${s}`},{id:e.videoRtx,attribute:"msid",value:`${s}-${h.MAIN} ${s}-bigvideo`}],a.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${s}-aux`;c.ssrcs=[{id:e.auxiliary,attribute:"cname",value:u},{id:e.auxiliary,attribute:"msid",value:`${u} ${s}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${u} ${s}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${u} ${s}-aux${h.VIDEO}`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(l=>l.mid).join(" ")),this._downlinkMIDMap.set(s,[n.mid,a.mid,c.mid])}removeDownlink(e,t){return p(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${t}) trying`),this.isReconnecting&&(yield this.waitForReconnected());let s=this._downlinkMIDMap.get(e),o=!1;this._peerConnection.getTransceivers().forEach(n=>{s!=null&&s.includes(Number(n.mid))&&(o=!0,n.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(n=>{s!=null&&s.includes(Number(n.mid))&&(o=!0,n.direction="inactive",n.ssrcs=[],n.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&o&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(e),this._log.info(`removeDownlink(${t}) done`)})}getDownlinkMids(e){return this._downlinkMIDMap.get(e)}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:o,auxVideo:n}=e;try{if(ts()){let a=this._peerConnection.getSenders().slice(0,4);for(let c=0;c<a.length;c++){let u=a[c],l;c===0&&t?l=t:c===1&&s?l=s:c===2&&o?l=o:c===3&&n&&(l=n),l&&(yield this.setSenderMaxBitrate(u,l))}}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth${a}`)}})}setSenderMaxBitrate(e,t){let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ue(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp));let a=X?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:X?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:X?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:X?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:X?t*1e3:t}]),s&&(n.media[2].bandwidth=[{type:a,limit:X?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:X?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:X?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:X?o*1e3:o}]);let c={type:"offer",sdp:We(n)};return this.updateSDP({localDescription:c})}updateSDP({isNeedToCreateOffer:e=!1,localDescription:t,tinyIdRemoving:s}){if(!this._parsedAnswer)return;let o=We(this._parsedAnswer);return this._updateSDPPromise=new Promise((n,a)=>p(this,null,function*(){var c,u;try{e&&this._peerConnection&&(this._log.info("creating offer"),t=yield this._peerConnection.createOffer()),t&&(yield this.setOffer(t)),yield this.setAnswer({type:"answer",sdp:o}),this._updateSDPPromise=null,n()}catch(l){this._log.error(l),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:m,currentDirection:f,direction:I,stopped:b})=>({mid:m,currentDirection:f,direction:I,stopped:b})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._log.warn(`local sdp: ${t==null?void 0:t.sdp}`||((c=this._peerConnection.localDescription)==null?void 0:c.sdp)),this._log.warn(`remote sdp: ${o}`||((u=this._peerConnection.remoteDescription)==null?void 0:u.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,a(l)}})),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:Wu(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}};y([Os()],Tr.prototype,"updateSDP",1);var yc=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},bc=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new yc(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Ku=new Set;function xi(){let r=Math.floor(Math.random()*4294967296);return Ku.has(r)?xi():(Ku.add(r),r)}var Qu=Ne(Me());var wi=class extends Qu.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_enableSEI");d(this,"_sei");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=A.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Zt&&(this._sei=new Jo(this,this._log,this._isUplink))}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(E.emit(_.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var Oc=class extends wi{constructor(e){super(M(N({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_audioManager");this._audioManager=e.audioManager,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(mt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){this.installEvents()}reset(){this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var a,c,u,l,m,f;if(!this.singlePC)return;if(yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new C({code:g.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264ENCODE})});Le&&at()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(yt["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),et()&&(yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s})),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),yield this.singlePC.setBandwidth({audio:((a=this.localMainAudioTrack)==null?void 0:a.profile.bitrate)||((c=this.localAuxAudioTrack)==null?void 0:c.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(m=(l=this.localMainVideoTrack)==null?void 0:l.small)==null?void 0:m.bitrate,auxVideo:(f=this.localAuxVideoTrack)==null?void 0:f.profile.bitrate}),yield this._signalChannel.sendWaitForResponse({command:W.SPC_PUBLISH,responseCommand:B.SPC_PUBLISH_RESULT,data:M(N({},this.singlePC.uplinkSSRC),{state:this.publishState})}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=this._audioManager.mixedAudioTrack,c=this._peerConnection.getTransceivers(),u=[],l=[];if(a){let f=c[0].sender.replaceTrack(a);l.push(0),u.push(f)}if(n)if(o){let f=c[3].sender.replaceTrack(n);l.push(3),u.push(f)}else{let f=c[1].sender.replaceTrack(n);l.push(1),u.push(f)}if(s){let f=c[2].sender.replaceTrack(s);l.push(2),u.push(f)}let m=this.setTransceiverDirection(K.SENDONLY,l);return u.push(m),Promise.all(u)}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(this._audioManager.mixedAudioTrack||(yield a[0].replaceTrack(null),c.push(0)),o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=M(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=M(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(K.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===g.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),tt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){var s;if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),mt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===K.INACTIVE&&(yield this.setTransceiverDirection(K.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),mt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)this._audioManager.mixedAudioTrack||(yield s[0].sender.replaceTrack(null));else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(K.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!X)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(u=>{n[u].direction!==e&&(n[u].direction=e,s=!0)}),s){this._log.info("updating offer");let u=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(u)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
  54. `).map(u=>{if(u.match(new RegExp(`a=(${K.INACTIVE}|${K.RECVONLY}|${K.SENDONLY})`))&&a++,t.includes(a)){if(e===K.INACTIVE&&u.includes(`a=${K.RECVONLY}`))return o=!0,`a=${e}`;if(e===K.SENDONLY&&u.includes(`a=${K.INACTIVE}`))return o=!0,`a=${K.RECVONLY}`}return u}).join(`\r
  55. `);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.mediaTrack;if(!t||t.length===0||!s)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${s.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(this._audioManager.mixedAudioTrack)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(e.outMediaTrack||s)),o&&t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)))})}setBandwidth(o){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(W.UPDATE_MUTE_STAT,s)}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(_.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Ei?(this._log.error(me.NOT_SUPPORTED_H264ENCODE),new C({code:g.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264ENCODE})})):new C({code:g.UNKNOWN,message:D({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},Dc=Oc;function qu(r){return Object.keys(r).filter(i=>r[i])}var an=class extends wi{constructor(e){super(M(N({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new wt(this._room,this),this.remoteVideoTrack=new ft(this._room,this),this.remoteAuxiliaryTrack=new cr(this._room,this),this.initialize()}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Qt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e;if(t.id.split("-")[0]!==this.tinyId)return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let c=h.AUDIO;s.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let u=this.remoteAudioTrack;c===h.VIDEO?u=this.remoteVideoTrack:c===h.AUXILIARY&&(u=this.remoteAuxiliaryTrack),u.setInputMediaStreamTrack(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info(`subscribe ${t} ${qu(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new C({code:g.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${qu(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:O.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&this.doSubscribe(this.subscribeState,!1)}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(!!this.singlePC){if(this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected(),t||!this.hasSSRC){let s={audioSsrc:xi(),bigVideoSsrc:xi(),bigVideoRtxSsrc:xi(),auxVideoSsrc:xi(),auxVideoRtxSsrc:xi()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:u}=s;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:u},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});let l=yield this._signalChannel.sendWaitForResponse({command:W.SPC_SUBSCRIBE,responseCommand:B.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:s}});if(l.data.code!==0)throw yield this.removeDownlink(),new C({code:l.data.code,message:l.data.message});return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}})}removeDownlink(){return p(this,null,function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))})}};y([G(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new C({code:g.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],an.prototype,"subscribe",1);var Xu=an;function zu(){return G(r=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;E.emit("61",{room:this}),i.forEach(t=>{t.kind==="audio"&&this.audioManager.addAudioTrack(t)});let e=r.apply(this,i);return i.forEach(t=>{var s;t.publish(this,e),t.kind==="audio"&&((s=this.audioManager.localMixAudioTrack)==null||s.publish(this,e))}),e})})}function Zu(){return G(r=>function(...i){i.forEach(t=>{t.kind==="audio"&&this.audioManager.removeAudioTrack(t)});let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var{isString:el,isPlainObject:uk,isUndefined:gr,getNetworkType:Gm,getTerminalType:Wm,isEmpty:Ds}=Ae,It=class extends on{constructor(e){super(e);this.privateMapKey="";this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this._signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=es;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._networkType=Gm();this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.enableHWEncoder=!1;this._stats=new Rs(this,this._log),this.userManager=new Lo(this.userId,this._log),this._version=Ie,this.sdpSemantics=Qi,gr(e.sdpSemantics)?Dt.isUnifiedPlanDefault()&&(this.sdpSemantics=jt):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${this._networkType}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=gr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!gr(e.enableSPC)&&es&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,s){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Lc(n,[]);E.emit(_.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this._joinOptions=e,new Promise((o,n)=>p(this,null,function*(){this._joinReject=n;try{this.checkDestroy();let a=yield this.initialize();yield this.doJoin(e,a),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(a){n(a)}this._joinReject=null}))})}doJoin(e,t=!1){return new Promise((s,o)=>p(this,null,function*(){var u,l,m;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(ce.SETUP_FAILED,f=>{this.clearJoinTimeout(),E.emit(_.JOIN_SIGNAL_CONNECTION_END,{room:this,error:f}),o(f)}),re((l=(u=this.scheduleResult)==null?void 0:u.config)==null?void 0:l.singlePC)&&es&&(this.enableSPC=this.scheduleResult.config.singlePC);let n;if(this.enableSPC&&!this.singlePC){this.singlePC=new Tr({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.once("error",()=>this.fallbackToMPC());try{n=yield this.singlePC.initialize()}catch(f){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Wm(),netType:Jt[this._networkType],bussinessInfo:this._businessInfo,ability:n};t&&(a.userSig=this.userSig),this._log.debug(`join room signal data: ${JSON.stringify(a)}`);let c=5e3;((m=this.scheduleResult.config)==null?void 0:m.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new C({code:g.JOIN_ROOM_FAILED,message:D({key:O.JOIN_ROOM_TIMEOUT})}))},c),E.emit(_.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,a),this._signalChannel.once(B.JOIN_ROOM_RESULT,f=>{this.clearJoinTimeout();let{code:I,message:b,data:k}=f.data;E.emit(_.JOIN_RECEIVED_CMD_RES,{room:this,code:I}),I===0?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=k.publishers,this.singlePC&&this.singlePC.connect(k.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${I} error: ${b}`),o(new C({code:g.JOIN_ROOM_FAILED,extraCode:I,message:D({key:O.JOIN_ROOM_FAILED,data:{error:b,code:I}})})))})}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{if(this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(M(N({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),q.logSuccessEvent({userId:this.userId,eventType:be.REJOIN}),this.singlePC){let e=t=>{var s;t.state==="CONNECTED"&&((s=this.singlePC)==null||s.off(St.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof Dc&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(o=>{o.installEvents(),o.doSubscribe()}))};this.singlePC.on(St.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Qo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),q.logFailedEvent({userId:this.userId,eventType:be.REJOIN,error:e}),this.emit("error",new C({code:g.JOIN_ROOM_FAILED,message:D({key:O.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this._signalChannel||Tu(this.userId),o=!!(s&&s.isConnected&&s.keepAlive);return this._log.info(`setup signal channel. reuse: ${+o}`),o?(s.url=e,s.backupUrl=t,s.room=this,this._signalChannel=s):this._signalChannel=new Ts({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this}),this._networkQuality||(this._networkQuality=new Mi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Mi.EVENT_NETWORK_QUALITY,n=>{this.emit("network-quality",n)})),Te(this,this._signalChannel).add(ce.CONNECTION_STATE_CHANGED,n=>{E.emit(_.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},n)),this.emit("signal-connection-state-changed",n)}).add(ce.RECONNECT_FAILED,n=>{this.reset(),this.emit("error",n)}).add(B.PEER_JOIN,n=>{let{srcTinyId:a,userId:c,role:u}=n.data.data;this.userManager.addUser({userId:c,tinyId:a,role:u})}).add(B.PEER_LEAVE,n=>{let{userId:a,reason:c=0}=n.data.data;this.userManager.deleteUser(a,c)}).add(B.UPDATE_REMOTE_MUTE_STAT,n=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(n.data)}).add(B.CLIENT_BANNED,n=>{let a=n.data.data,{reason:c}=a;if(q.uploadEvent({log:`stat-banned:${c}`,userId:this.userId}),c==="user_time_out"){this._log.warn(`${c} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[c==="kick"?"error":"info"](`user was banned because of [${c}]`),this.reset(),this.emit("banned",{reason:c})}),this._signalChannel.once(ce.SETUP_SUCCESS,n=>{this.tinyId=n.signalInfo.tinyId,E.emit(_.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(_.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(this._isUsingCachedSchedule?10*1e3:void 0),o})}setSignalChannel(e){this._signalChannel=e,e||ne(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(_.LEAVE_SEND_CMD,{room:this}),(e=this._signalChannel)==null||e.send(W.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Z.run(dt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Z.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this._signalChannel)!=null&&a.isConnected))return;let s=this._signalChannel.isConnected?Jd(this.userId):[],o=N({str_sdk_version:pi,uint64_datetime:new Date().getTime(),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:Jt[this._networkType]},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t);E.emit(_.HEARTBEAT_REPORT,{room:this,report:o}),this._signalChannel.send(W.ON_QUALITY_REPORT,o),this.emit("heartbeat-report",M(N({},o),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let n=Date.now();this._lastHeartBeatTime>0&&n-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${n-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=n),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:o,flag:n})=>{let a=this.remotePublishedUserMap.get(s);return a&&this._changeBigSmallRecords.has(s)&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});E.emit(_.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let o=new(this.singlePC?Xu:lc)({userId:e,tinyId:t,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,e),this.emit("remote-published",o)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("sei-message",s=>{this.emit("sei-message",s)}),e.on("error",s=>{let o=s.getCode();o!==g.ICE_TRANSPORT_ERROR&&(o===g.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",M(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Z.run(dt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Z.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:W.GET_USER_LIST,responseCommand:B.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:u})=>({userId:a,tinyId:c,role:u}));throw D({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.USER_LIST_RES,code:s,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!nc)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){this.singlePC||this.getAllConnections().forEach(t=>{if(t instanceof Ue&&!t.getIsReconnecting()){let s=t.getPeerConnection();s&&s.connectionState===te.CLOSED&&(this._log.warn(`[${t.getUserId()}] pc is closed but not reconnect`),t.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),q.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,yield this.reJoin(),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Qo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach(t=>{let s=new lc({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.subscribe(t.subscribeState,"auxiliary")})})}destroy(){this._isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new C({code:g.INVALID_OPERATION,message:D({key:O.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:B.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this._signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new C({code:g.SWITCH_ROLE_FAILED,message:D({key:O.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof C&&s.getCode()===g.API_CALL_TIMEOUT&&(s=new C({code:g.SWITCH_ROLE_FAILED,message:D({key:O.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return p(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof ve&&(c instanceof xt?s.audio=c:t.audio=c),c instanceof ke&&(c instanceof xe&&c.mediaType===2?s.video=c:t.video=c)});let o=Ds(t),n=Ds(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Dc({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Qo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",M(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let u=c.getCode();u!==g.ICE_TRANSPORT_ERROR&&(u===g.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||(o instanceof ve&&(o instanceof xt?s.audio=o:t.audio=o),o instanceof ke&&(o instanceof xe&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Ds(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Ds(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(o){}this.localTracks.size===0&&!this.audioManager.mixedAudioTrack&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{E.emit(_.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(_.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Yo(n)}] prev: [${Yo(s.subscribeState)}]`),yield s.subscribe(n,o);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());s.remoteVideoTrack.setMediaType(n.smallVideo?8:4),E.emit(_.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof C?n.getCode():g.UNKNOWN,c=n;throw n instanceof C?a===g.REMOTE_STREAM_NOT_EXIST&&(c=new C({code:g.API_CALL_ABORTED,message:D({key:O.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new C({code:a,message:D({key:O.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(_.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,Z.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(_.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run(jr,()=>{var o;let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e})}getLocalVideoStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:s,framesEncoded:o,framesSent:n,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:s,framesEncoded:o,framesSent:n,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(Ae.getTurnServer(o))):Ae.isPlainObject(e)&&s.push(Ae.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.START_PUBLISH_TENCENT_CDN_RES:B.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.STOP_PUBLISH_TENCENT_CDN_RES:B.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this._signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:B.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Ae.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let t=e==null?void 0:e.muteState.hasSmall,s=e==null?void 0:e.muteState.hasVideo;if(!t&&!s||!e.isBigStreamSubscribed&&!e.isSmallStreamSubscribed)return;let o=e.getUserId(),n=this._changeBigSmallRecords.get(o)||{},{subscribeState:a}=e,{options:c,isSubscribing:u,reSubscribeCount:l}=n;if(c.video&&a.video||c.smallVideo&&a.smallVideo&&t||u)return;let m={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};if(t&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{c&&!u&&l>=1&&(n.isSubscribing=!0,n.reSubscribeCount=l-1,!t&&e.isSmallStreamSubscribed&&(m.video=!0,m.smallVideo=!1),yield e==null?void 0:e.subscribe(m,"main"),e.remoteVideoTrack.setMediaType(m.smallVideo?8:4),this._log.info(`change [${o}] to ${m.smallVideo?"small":"big"} video successfully. count ${Xi-n.reSubscribeCount}.`),n.isSubscribing=!1,n.reSubscribeCount=Xi)}catch(f){this._log.info(`change [${o}] to ${m.smallVideo?"small":"big"} video failed. count ${Xi-n.reSubscribeCount}.`),n.isSubscribing=!1,l===0&&this._changeBigSmallRecords.delete(o)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Xi};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(el(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!gr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new C({code:g.INVALID_PARAMETER,message:D({key:O.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new C({code:g.INVALID_PARAMETER,message:D({key:O.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!gr(e.userDefinePushArgs))if(el(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new C({code:g.INVALID_PARAMETER,message:D({key:O.INVALID_USER_DEFINE_PUSH_ARGS})});Ds(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){var s;(s=this.uplinkConnection)==null||s.sendSEI(e,t)}};y([ee(["left",L.INIT],"joined"),fr({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this._isDestroyed?(this._log.warn("is using cached schedule, retry join"),ci(!0),this.reset(),i()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),i()):(this.reset(),this._log.error(r),e(r))}}),mu()],It.prototype,"join",1),y([ee("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),pu(),$u("leave room"),Cs({fnName:"publish",validateArgs:!1}),Cs({fnName:"unsubscribe",validateArgs:!1})],It.prototype,"leave",1),y([Os(),zu(),fr({settings:{retries:Ot,timeout:r=>He(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),E.emit(_.PUBLISH_FAILED,{room:this}))}})],It.prototype,"publish",1),y([Cs({fnName:"publish",callback(...r){var i;this.localTracks.size===0&&((i=this.uplinkConnection)==null||i.close("you unpublished"),this.uplinkConnection=null,r.forEach(e=>e.unpublish()))}}),Bu("api-call"),Os(),Zu()],It.prototype,"unpublish",1),y([Rc((...r)=>r[0].userId),_u(),fr({settings:{retries:Ot,timeout:r=>He(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),E.emit(_.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],It.prototype,"subscribe",1),y([Cs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Rc((...r)=>r[0].userId)],It.prototype,"unsubscribe",1);Es.create=Es._create.bind(Es,It);var fk=Es;export{fk as default};