trtc-sdk-v5 5.2.0 → 5.2.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -1,43 +1,43 @@
1
- var il=Object.create;var Ir=Object.defineProperty,rl=Object.defineProperties,Dc=Object.getOwnPropertyDescriptor,sl=Object.getOwnPropertyDescriptors,ol=Object.getOwnPropertyNames,vs=Object.getOwnPropertySymbols,vc=Object.getPrototypeOf,an=Object.prototype.hasOwnProperty,Lc=Object.prototype.propertyIsEnumerable,nl=Reflect.get;var Ls=Math.pow,nn=(r,t,e)=>t in r?Ir(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,N=(r,t)=>{for(var e in t||(t={}))an.call(t,e)&&nn(r,e,t[e]);if(vs)for(var e of vs(t))Lc.call(t,e)&&nn(r,e,t[e]);return r},M=(r,t)=>rl(r,sl(t));var Mc=(r,t)=>{var e={};for(var i in r)an.call(r,i)&&t.indexOf(i)<0&&(e[i]=r[i]);if(r!=null&&vs)for(var i of vs(r))t.indexOf(i)<0&&Lc.call(r,i)&&(e[i]=r[i]);return e};var Sr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),gr=(r,t)=>{for(var e in t)Ir(r,e,{get:t[e],enumerable:!0})},al=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ol(t))!an.call(r,s)&&s!==e&&Ir(r,s,{get:()=>t[s],enumerable:!(i=Dc(t,s))||i.enumerable});return r};var Ne=(r,t,e)=>(e=r!=null?il(vc(r)):{},al(t||!r||!r.__esModule?Ir(e,"default",{value:r,enumerable:!0}):e,r));var y=(r,t,e,i)=>{for(var s=i>1?void 0:i?Dc(t,e):t,o=r.length-1,n;o>=0;o--)(n=r[o])&&(s=(i?n(t,e,s):n(s))||s);return i&&s&&Ir(t,e,s),s};var d=(r,t,e)=>(nn(r,typeof t!="symbol"?t+"":t,e),e);var At=(r,t,e)=>nl(vc(r),e,t);var p=(r,t,e)=>new Promise((i,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?i(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(r,t)).next())});var Me=Sr((Ym,cn)=>{"use strict";var cl=Object.prototype.hasOwnProperty,Ie="~";function Ar(){}Object.create&&(Ar.prototype=Object.create(null),new Ar().__proto__||(Ie=!1));function dl(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Pc(r,t,e,i,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new dl(e,i||r,s),n=Ie?Ie+t:t;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,t){--r._eventsCount===0?r._events=new Ar:delete r._events[t]}function fe(){this._events=new Ar,this._eventsCount=0}fe.prototype.eventNames=function(){var t=[],e,i;if(this._eventsCount===0)return t;for(i in e=this._events)cl.call(e,i)&&t.push(Ie?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};fe.prototype.listeners=function(t){var e=Ie?Ie+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,o=i.length,n=new Array(o);s<o;s++)n[s]=i[s].fn;return n};fe.prototype.listenerCount=function(t){var e=Ie?Ie+t:t,i=this._events[e];return i?i.fn?1:i.length:0};fe.prototype.emit=function(t,e,i,s,o,n){var a=Ie?Ie+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,m;if(c.fn){switch(c.once&&this.removeListener(t,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,i),!0;case 4:return c.fn.call(c.context,e,i,s),!0;case 5:return c.fn.call(c.context,e,i,s,o),!0;case 6:return c.fn.call(c.context,e,i,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,g;for(m=0;m<f;m++)switch(c[m].once&&this.removeListener(t,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,i);break;case 4:c[m].fn.call(c[m].context,e,i,s);break;default:if(!l)for(g=1,l=new Array(u-1);g<u;g++)l[g-1]=arguments[g];c[m].fn.apply(c[m].context,l)}}return!0};fe.prototype.on=function(t,e,i){return Pc(this,t,e,i,!1)};fe.prototype.once=function(t,e,i){return Pc(this,t,e,i,!0)};fe.prototype.removeListener=function(t,e,i,s){var o=Ie?Ie+t:t;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)&&(!i||n.context===i)&&Ms(this,o);else{for(var a=0,c=[],u=n.length;a<u;a++)(n[a].fn!==e||s&&!n[a].once||i&&n[a].context!==i)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:Ms(this,o)}return this};fe.prototype.removeAllListeners=function(t){var e;return t?(e=Ie?Ie+t:t,this._events[e]&&Ms(this,e)):(this._events=new Ar,this._eventsCount=0),this};fe.prototype.off=fe.prototype.removeListener;fe.prototype.addListener=fe.prototype.on;fe.prefixed=Ie;fe.EventEmitter=fe;typeof cn!="undefined"&&(cn.exports=fe)});var nc=Sr((fN,Su)=>{var Iu=Su.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 t="candidate:%s %d %s %d %s %d typ %s";return t+=r.raddr!=null?" raddr %s rport %d":"%v%v",t+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(t+=" generation %d"),t+=r["network-id"]!=null?" network-id %d":"%v",t+=r["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var t="ssrc:%d";return r.attribute!=null&&(t+=" %s",r.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(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(Iu).forEach(function(r){var t=Iu[r];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ru=Sr($t=>{var pr=function(r){return String(Number(r))===r?Number(r):r},fm=function(r,t,e,i){if(i&&!e)t[i]=pr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(t[e[s]]=pr(r[s+1]))},Em=function(r,t,e){var i=r.name&&r.names;r.push&&!t[r.push]?t[r.push]=[]:i&&!t[r.name]&&(t[r.name]={});var s=r.push?{}:i?t[r.name]:t;fm(e.match(r.reg),s,r.names,r.name),r.push&&t[r.push].push(s)},gu=nc(),Tm=RegExp.prototype.test.bind(/^([a-z])=(.*)/);$t.parse=function(r){var t={},e=[],i=t;return r.split(/(\r\n|\r|\n)/).filter(Tm).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),i=e[e.length-1]);for(var a=0;a<(gu[o]||[]).length;a+=1){var c=gu[o][a];if(c.reg.test(n))return Em(c,i,n)}}),t.media=e,t};var Au=function(r,t){var e=t.split(/=(.+)/,2);return e.length===2?r[e[0]]=pr(e[1]):e.length===1&&t.length>1&&(r[e[0]]=void 0),r};$t.parseParams=function(r){return r.split(/;\s?/).reduce(Au,{})};$t.parseFmtpConfig=$t.parseParams;$t.parsePayloads=function(r){return r.toString().split(" ").map(Number)};$t.parseRemoteCandidates=function(r){for(var t=[],e=r.split(" ").map(pr),i=0;i<e.length;i+=3)t.push({component:e[i],ip:e[i+1],port:e[i+2]});return t};$t.parseImageAttributes=function(r){return r.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(Au,{})})};$t.parseSimulcastStreamList=function(r){return r.split(";").map(function(t){return t.split(",").map(function(e){var i,s=!1;return e[0]!=="~"?i=pr(e):(i=pr(e.substring(1,e.length)),s=!0),{scid:i,paused:s}})})}});var Nu=Sr((TN,Cu)=>{var ac=nc(),Im=/%[sdv%]/g,Sm=function(r){var t=1,e=arguments,i=e.length;return r.replace(Im,function(s){if(t>=i)return s;var o=e[t];switch(t+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Ss=function(r,t,e){var i=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,s=[r+"="+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var n=t.names[o];t.name?s.push(e[t.name][n]):s.push(e[t.names[o]])}else s.push(e[t.name]);return Sm.apply(null,s)},gm=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Am=["i","c","b","a"];Cu.exports=function(r,t){t=t||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=t.outerOrder||gm,i=t.innerOrder||Am,s=[];return e.forEach(function(o){ac[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",ac.m[0],o)),i.forEach(function(n){ac[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
1
+ var rl=Object.create;var Ir=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?Ir(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 Ar=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),Rr=(r,i)=>{for(var e in i)Ir(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&&Ir(r,s,{get:()=>i[s],enumerable:!(t=vc(i,s))||t.enumerable});return r};var ye=(r,i,e)=>(e=r!=null?rl(kc(r)):{},cl(i||!r||!r.__esModule?Ir(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&&Ir(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 Le=Ar((Jm,un)=>{"use strict";var dl=Object.prototype.hasOwnProperty,Se="~";function Cr(){}Object.create&&(Cr.prototype=Object.create(null),new Cr().__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 Cr:delete r._events[i]}function Ee(){this._events=new Cr,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 Cr,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=Ar((fN,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=Ar($t=>{var fr=function(r){return String(Number(r))===r?Number(r):r},pm=function(r,i,e,t){if(t&&!e)i[t]=fr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=fr(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]]=fr(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(fr),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=fr(e):(t=fr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var yu=Ar((TN,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
2
  `)+`\r
3
- `}});var cc=Sr(Ht=>{var vi=Ru(),Rm=Nu();Ht.write=Rm;Ht.parse=vi.parse;Ht.parseFmtpConfig=vi.parseFmtpConfig;Ht.parseParams=vi.parseParams;Ht.parsePayloads=vi.parsePayloads;Ht.parseRemoteCandidates=vi.parseRemoteCandidates;Ht.parseImageAttributes=vi.parseImageAttributes;Ht.parseSimulcastStreamList=vi.parseSimulcastStreamList});import pL from"webrtc-adapter";var lu=Ne(Me());var kc=(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))(kc||{}),I=kc;var ul=function(r){for(let t in I)if(I[t]===r)return t;return"UNKNOWN"},dn=class extends Error{constructor({name:e="RtcError",message:i,code:s=I.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${ul(s)} 0x${s.toString(16)}>`,c=`${i}${n?` constraint: ${n}`:""}${i!=null&&i.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=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},C=dn;var xc=new Date().getTime(),un=0,wc=function(r){xc=r,un=xc-new Date().getTime();let t=new Date;t.setTime(r),A.info(`baseTime from server: ${t} offset: ${un}`)},Rr=function(){return new Date().getTime()+un},Ps=function(){let r=new Date;return r.setTime(Rr()),r.toLocaleString()};var ge={};gr(ge,{bytes2ms:()=>Jl,copyProperties:()=>Kl,deepMerge:()=>lt,env:()=>Kt,fibonacci:()=>Zi,formatedTime:()=>eh,getConstructorName:()=>uo,getContainerFromElement:()=>lo,getEnv:()=>Gl,getInternalVersion:()=>Xl,getLoggerUrl:()=>Ii,getMuteStateFromFlag:()=>Xt,getNetworkQuality:()=>ql,getNetworkType:()=>co,getOSType:()=>Yc,getReconnectionTimeout:()=>Fe,getStringByteLength:()=>ho,getSysInfo:()=>Wl,getTerminalType:()=>jc,getTurnServer:()=>zl,getValueType:()=>oe,glog:()=>qc,ipv4ToUint32:()=>zr,isArray:()=>de,isArrayOrObject:()=>Yr,isAudioWorkletSupported:()=>Un,isBoolean:()=>ie,isConstructor:()=>Qr,isEmpty:()=>qr,isFunction:()=>j,isLangChinese:()=>ut,isMediaStreamTrack:()=>Yl,isNumber:()=>q,isObject:()=>Si,isOverseaSdkAppId:()=>ao,isPlainObject:()=>He,isPromise:()=>Xr,isRemoteTrack:()=>Yt,isString:()=>Y,isUndefined:()=>T,ms2bytes:()=>jl,ms2samples:()=>Qc,performanceNow:()=>$,promiseAny:()=>Bn,samples2ms:()=>Xc,stringify:()=>ze,stringifyIncludeValue:()=>$n});var Kt={};gr(Kt,{ANDROID_VERSION:()=>mn,CHROME_MAJOR_VERSION:()=>mi,CHROME_VERSION:()=>Qs,EDGE_VERSION:()=>xs,EDG_MAJOR_VERSION:()=>_n,EDG_VERSION:()=>ws,FIREFOX_MAJOR_VERSION:()=>pn,FIREFOX_VERSION:()=>ks,HUAWEI_VERSION:()=>Js,IE_VERSION:()=>_l,IOS_MAIN_VERSION:()=>In,IOS_VERSION:()=>Wt,IPADQQB_VERSION:()=>Ws,IS_ANDROID:()=>Pe,IS_ANDROID_WEBVIEW:()=>Il,IS_ANY_SAFARI:()=>Tn,IS_CHROME:()=>Gi,IS_CHROME_OS:()=>Hc,IS_CHROMIUM_BASE:()=>wr,IS_EDG:()=>Bi,IS_EDGE:()=>Ui,IS_ELECTRON:()=>El,IS_FIREFOX:()=>Q,IS_HEADLESS_CHROME:()=>En,IS_HUAWEI:()=>Tl,IS_HUAWEIBROWSER:()=>Mr,IS_IE:()=>$c,IS_IE8:()=>pl,IS_IOS:()=>Je,IS_IOS_13_OR_14:()=>Sl,IS_IOS_15_1:()=>Vr,IS_IPAD:()=>Vi,IS_IPADQQB:()=>Dr,IS_IPAD_PRO:()=>hn,IS_IPHONE:()=>Gt,IS_IPOD:()=>Bc,IS_LINUX:()=>vr,IS_LOCAL:()=>Ye,IS_MAC:()=>je,IS_MACQQB:()=>Or,IS_MIBROWSER:()=>Lr,IS_MQQB:()=>Fi,IS_NATIVE_ANDROID:()=>ml,IS_OLD_ANDROID:()=>hl,IS_OPPOBROWSER:()=>kr,IS_SAFARI:()=>$e,IS_SAFARI_15_1:()=>Sn,IS_SAMSUNGBROWSER:()=>Pr,IS_SOGOU:()=>Nr,IS_SOGOUM:()=>Cr,IS_TBS:()=>nt,IS_UCBROWSER:()=>fn,IS_VIVOBROWSER:()=>xr,IS_WECHAT:()=>$i,IS_WIN:()=>Rt,IS_WQQB:()=>br,IS_WX:()=>fl,IS_X5MQQB:()=>Hi,IS_XWEB:()=>yr,MACQQB_VERSION:()=>Gs,MI_VERSION:()=>Ks,MQQB_VERSION:()=>wi,OPPO_VERSION:()=>Ys,SAFARI_VERSION:()=>Wi,SAMSUNG_VERSION:()=>js,SOGOUM_VERSION:()=>Vs,SOGOU_VERSION:()=>Us,TBS_VERSION:()=>Bs,USER_AGENT:()=>Ke,VIVO_VERSION:()=>Xs,WECHAT_VERSION:()=>Hs,WQQB_VERSION:()=>Fs,XWEB_VERSION:()=>$s,browserInfo:()=>ot,getBrowserInfo:()=>Fc,getChromeMajorVersion:()=>at,getOSName:()=>qs,getOSString:()=>gn,getUserAgentData:()=>Ur,isLocalStorageEnabled:()=>Ct});var Ke=typeof navigator=="undefined"?"":navigator.userAgent,F=r=>new RegExp(r,"i").test(Ke),le=r=>{if(F(r)){let t=new RegExp(`${r}\\/([\\d.]+)`),e=Ke.match(t);if(e&&e[1])return e[1]}return""},ln=r=>{if(F(r)){let t=new RegExp(`${r}\\/(\\d+)`),e=Ke.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},Vc=/AppleWebKit\/([\d.]+)/i.exec(Ke),ll=Vc?parseFloat(Vc[1]):NaN,Vi=F("iPad"),hn=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&F("Macintosh"),Gt=F("iPhone")&&!Vi,Bc=F("iPod"),Je=Gt||Vi||Bc||hn,Pe=F("Android"),mn=function(){if(Pe){let r=Ke.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(r){let t=r[1]&&parseFloat(r[1]),e=r[2]&&parseFloat(r[2]);if(t&&e)return parseFloat(`${r[1]}.${r[2]}`);if(t)return t}}return NaN}(),hl=Pe&&F("webkit")&&mn<2.3,ml=Pe&&mn<5&&ll<537,Q=F("Firefox"),ks=le("Firefox"),pn=ln("Firefox"),Ui=F("Edge"),xs=le("Edge"),Bi=F("Edg"),ws=le("Edg"),_n=ln("Edg"),Cr=F("SogouMobileBrowser"),Vs=le("SogouMobileBrowser"),Nr=F("MetaSr\\s"),Us=le("MetaSr\\s"),nt=F("TBS"),Bs=le("TBS"),yr=F("XWEB"),$s=le("XWEB"),pl=F("MSIE\\s8\\.0"),$c=F("MSIE\\/\\d+"),_l=function(){if($c){let r=/MSIE\s(\d+)\.\d/.exec(Ke),t=r&&parseFloat(r[1]);return!t&&/Trident\/7.0/i.test(Ke)&&/rv:11.0/.test(Ke)&&(t=11),t}return NaN}(),$i=F("(micromessenger|webbrowser)"),Hs=le("MicroMessenger"),Hi=!nt&&F("MQQBrowser")&&F("COVC"),Fi=!nt&&F("MQQBrowser")&&!F("COVC"),wi=Fi||Hi?le("MQQBrowser"):"",br=!nt&&F(" QQBrowser"),Fs=le(" QQBrowser"),Or=!nt&&F("QQBrowserLite"),Gs=le("QQBrowserLite"),Dr=!nt&&F("MQBHD"),Ws=le("MQBHD"),Rt=F("Windows"),je=!Je&&F("MAC OS X"),vr=!Pe&&F("Linux"),Hc=F("CrOS"),fl=F("MicroMessenger"),fn=F("UCBrowser"),El=F("Electron"),Lr=F("MiuiBrowser"),Ks=le("MiuiBrowser"),Mr=F("HuaweiBrowser"),Tl=F("Huawei"),Js=le("HuaweiBrowser"),Pr=F("SamsungBrowser"),js=le("SamsungBrowser"),kr=F("HeyTapBrowser"),Ys=le("HeyTapBrowser"),xr=F("VivoBrowser"),Xs=le("VivoBrowser"),at=()=>ln("Chrome"),wr=F("Chrome"),Gi=!Ui&&!Nr&&!Cr&&!nt&&!yr&&!Bi&&!br&&!Lr&&!Mr&&!Pr&&!kr&&!xr&&wr,En=F("HeadlessChrome"),mi=at(),Qs=le("Chrome"),$e=!wr&&!Fi&&!Hi&&!Or&&!Dr&&F("Safari"),Tn=$e||Je,Wi=le("Version"),Il=/Android.*(wv|.0.0.0)/.test(Ke),Wt=(()=>{if(hn)return Wi;if(Je){let r=Ke.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let t=r[1];return r[2]&&(t+=`.${r[2]}`),t}}return""})(),In=Number(Wt.split(".")[0]),Sn=Wi==="15.1",Vr=Wt==="15.1",Sl=(()=>{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(t){r=!1}return r}})(),ot=Fc();function Fc(){let r=new Map([[Q,["Firefox",ks]],[Bi,["Edg",ws]],[Gi,["Chrome",Qs]],[$e,["Safari",Wi]],[nt,["TBS",Bs]],[yr,["XWEB",$s]],[$i&&Gt,["WeChat",Hs]],[br,["QQ(Win)",Fs]],[Fi,["QQ(Mobile)",wi]],[Hi,["QQ(Mobile X5)",wi]],[Or,["QQ(Mac)",Gs]],[Dr,["QQ(iPad)",Ws]],[Lr,["MI",Ks]],[Mr,["HW",Js]],[Pr,["Samsung",js]],[kr,["OPPO",Ys]],[xr,["VIVO",Xs]],[Ui,["EDGE",xs]],[Cr,["SogouMobile",Vs]],[Nr,["Sogou",Us]]]),t="unknown",e="unknown";return r.has(!0)&&([t,e]=r.get(!0)),{name:t,version:e}}var ye=null;function Ur(){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 Uc=new Map([[Pe,"Android"],[Je,"iOS"],[Rt,"Windows"],[je,"MacOS"],[vr,"Linux"],[Hc,"ChromeOS"]]),qs=function(){return Uc.get(!0)?Uc.get(!0):ye?ye.platform:"unknown"},gn=()=>{let r=qs();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 Vn={};gr(Vn,{AUDIO_MUTE_BIT:()=>ro,AUDIO_STAT_BIT:()=>ji,AUX_STAT_BIT:()=>Hr,AUX_STREAM_MSID:()=>Dn,BACKEND_ENV:()=>io,BASE_DOC_URL:()=>ct,BASE_HOST:()=>zs,CAPABILITIES_KEYS:()=>no,CLASS_NAME:()=>Ul,CLOUD_CONSOLE_URL:()=>Al,DATA_FREEZE_TIMING:()=>oo,DOC_URL:()=>Rl,DTLS_STATE_UNKNOWN:()=>Qe,ENV_NAME:()=>Nt,EXCHANGE_SDP_TIMEOUT:()=>kn,INTERVAL:()=>jr,IS_WORKER:()=>Ki,IS_WORKLET:()=>Br,KIBANA_EVENT:()=>be,LOCAL_STREAM_PUBLISH_STATE:()=>Kc,LOGGER_CMD_TYPE:()=>fi,LOGGER_DOMAIN:()=>Nn,LOGGER_DOMAIN_OVERSEA:()=>yn,LOG_LEVEL:()=>Xe,LOG_LEVEL_NAME:()=>$l,MAIN_STREAM_MSID:()=>Fr,MICROPHONE_COMMUNICATIONS:()=>Bl,MICROPHONE_DEFAULT:()=>Ti,NAME:()=>h,NETWORK_TYPE:()=>Jt,NOT_SUPPORTED_H264:()=>Ei,PAUSED_RETRY_COUNT:()=>xn,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Wr,PEER_CONNECTION_STATE:()=>te,PEER_LEAVE_REASON:()=>wn,RAF:()=>Jr,RECOVER_CAPTURE_INTERVAL:()=>qi,REMOTE_STREAM_TYPE_AUX:()=>Ln,REMOTE_STREAM_TYPE_MAIN:()=>vn,RENDER_FREEZE_TIMING:()=>kl,RIC:()=>dt,SCHEDULE_DOMAIN:()=>Xi,SCHEDULE_TIMEOUT:()=>Vl,SDP_SEMANTICS_PLAN_B:()=>Yi,SDP_SEMANTICS_UNIFIED_PLAN:()=>jt,SECOND_HOST:()=>Rn,SIGNAL_PING_PONG_INTERVAL:()=>Nl,SIGNAL_PING_TIMEOUT:()=>Cl,SIGNAL_RECONNECTION_COUNT:()=>Gr,SMALL_STAT_BIT:()=>On,SPEAKER_DEFAULT:()=>Kr,STORAGE_EXPIRES_TIME:()=>Zs,STREAM_TYPE_BIG:()=>xl,STREAM_TYPE_SMALL:()=>wl,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Qi,SYNC_USER_LIST_INTERVAL:()=>Pl,Scene:()=>bt,Switch:()=>Gc,THIRD_HOST:()=>Cn,TIMEOUT:()=>zi,TRANSPORT_DIRECTION:()=>K,TRTC_ERROR_ASSISTANCE:()=>bn,TRTC_QUALITY_BAD:()=>vl,TRTC_QUALITY_DISCONNECTED:()=>Ml,TRTC_QUALITY_EXCELLENT:()=>bl,TRTC_QUALITY_GOOD:()=>Ol,TRTC_QUALITY_POOR:()=>Dl,TRTC_QUALITY_UNKNOWN:()=>yl,TRTC_QUALITY_VERY_BAD:()=>Ll,UPDATE_OFFER_TIMEOUT:()=>Pn,VIDEO_MUTE_BIT:()=>so,VIDEO_STAT_BIT:()=>Ji,audioProfileMap:()=>eo,getRetryCount:()=>Ot,getScriptDir:()=>gl,innerVersion:()=>pi,loggerProxy:()=>$r,screenProfileMap:()=>to,setLoggerProxy:()=>_i,setRetryCount:()=>Mn,setVersion:()=>An,version:()=>Se,videoProfileMap:()=>yt});var pi="4.15.00.1600",Se="5.0.0";function An(r){Se=r;let[t,e,i]=r.split(".").map(s=>parseInt(s,10));pi=`${t}.${Math.min(15,e)}.${Math.min(15,i)}.${e.toString().padStart(2,"0")}${i.toString().padStart(2,"0")}`}var Ki=typeof importScripts!="undefined",Br=typeof registerProcessor!="undefined",gl=()=>{let r=Ki?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},$r="",_i=r=>$r=r,zs="web.sdk.qcloud.com",Rn="web.sdk.tencent.cn",Cn="web.sdk.cloud.tencent.cn",Al="https://console.cloud.tencent.com/trtc",ct=`https://${zs}/trtc/webrtc/v5/doc`,Rl=`${ct}/zh-cn/`,Nn="https://yun.tim.qq.com",yn="https://apisgp.my-imcloud.com",bn="trtc_error_assistance",fi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},Nt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Xe=(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))(Xe||{}),Cl=18e3,Nl=2e3,Jt={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},Zs=7*24*3600*1e3,Gc=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(Gc||{}),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,On=2,Hr=4,ji=8,ro=64,so=16,Fr="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Dn="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",vn=h.MAIN,Ln=h.AUXILIARY,yl=0,bl=1,Ol=2,Dl=3,vl=4,Ll=5,Ml=6,Qe="unknown",te={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Wc=1/0;function Mn(r){Wc=r}function Ot(){return Wc}var Gr=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,Pn=1e4,kn=1e4,jt="unified-plan",Yi="plan-b",Ei=1028,Kc=(i=>(i[i.UNPUBLISH=-1]="UNPUBLISH",i[i.PUBLISHING=0]="PUBLISHING",i[i.PUBLISHED=1]="PUBLISHED",i))(Kc||{}),oo=500,kl=1e3,xl=h.BIG,wl=h.SMALL,Wr=10*1e3,Xi={MAIN:"schedule.rtc.qq.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},Vl=2e3,Ul={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},xn=5,Ti="default",Kr=Ti,Bl="communications",$l=Object.keys(Xe),wn=["normal leave","timeout leave","kick","role change"],Qi=10,qi=2e3,dt="ric",Jr="raf",jr="interval",zi="timeout",no=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId"];var qe=1e8;var Fl="trtc_env",Gl=function(){return new URLSearchParams(location.search).get(Fl)||""},ao=r=>Number(r)<14e8,Ii=function(r,t){let e;$r?e=$r:e=ao(r)?yn:Nn;let i=Math.floor(Math.random()*Ls(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${i}&sdkappid=${r}&cmdtype=${t}`};function jc(){return Pe?4:Gt?2:Vi?3:je?12:Rt?5:vr?13:1}function Yc(){return Pe?"Android":Gt?"iPhone":Vi?"iPad":je?"Mac":Rt?"Windows":vr?"Linux":"unknown"}function co(){let{userAgent:r,connection:t}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let i=t&&t.type&&t.type.toLowerCase(),s=t&&t.effectiveType&&t.effectiveType.toLowerCase();s==="slow-2"&&(s="2g");let o=e||"unknown";if(i)switch(i){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 Wl=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:jc(),uint32_device_type:0,str_os_verion:Yc(),uint32_link_type:1,str_client_version:pi,uint32_net_type:Jt[co()],ua:navigator.userAgent,version:""}}}};function Kl(r,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let i=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(r,e,i)}return r}function Jl(r,t=48e3){return Xc(r/4,t)}function Xc(r,t=48e3){return r*1e3/t}function jl(r,t=48e3){return Qc(r,t)*4}function Qc(r,t=48e3){return r*t/1e3}var qc=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},ut=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},He=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let t=Object.getPrototypeOf(r);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Zi(r,t=1,e=1){return r<=1?e:Zi(r-1,e,t+e)}function Fe(r){return r>8?30*1e3:Zi(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",ie=r=>typeof r=="boolean",Si=r=>oe(r)==="object",de=r=>oe(r)==="array",Yl=r=>oe(r)==="MediaStreamTrack".toLowerCase(),Yt=r=>r.isRemote,Xr=r=>oe(r)==="promise",Qr=r=>j(r)&&r.prototype.constructor===r,uo=r=>Qr(r)?r.prototype.constructor.name:"",Un=typeof AudioWorkletNode!="undefined";function Bn(r){return new Promise((t,e)=>{let i=[];r.forEach(s=>{s.then(t).catch(o=>{i.push(o),i.length===r.length&&e(i)})})})}function $(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Jc=r=>+r<10?`0${r}`:r,Xl=r=>{let t=r.match(/^\d+\.\d+\.\d+/)[0];if(!t)return r;let e=t.split("."),i=Jc(e[1])+Jc(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${i}`},Ql=Object.prototype.hasOwnProperty,{toString:np}=Object.prototype;function qr(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(He(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 t in r)if(Ql.call(r,t))return!1;return!0}}return!1}function Xt(r,t){return{userId:t,hasAudio:!!(r&ji),hasVideo:!!(r&Ji),hasAuxiliary:!!(r&Hr),hasSmall:!!(r&On),audioMuted:!!(r&ro),videoMuted:!!(r&so),audioAvailable:!!(r&ji)&&!(r&ro),videoAvailable:!!(r&Ji)&&!(r&so)}}function ql(r,t){return r>50||t>500?5:r>30||t>350?4:r>20||t>200?3:r>10||t>100?2:r>=0||t>=0?1:0}function zl(r){let t={urls:`turn:${r.url}`};return!T(r.username)&&!T(r.credential)&&(t.username=r.username,t.credential=r.credential,t.credentialType="password",T(r.credentialType)||(t.credentialType=r.credentialType)),t}function zr(r,t=!0){if(!Y(r))return 0;let e=r.split(".");return t?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Yr=function(r){return de(r)||Si(r)},lt=function(r,t,e,i){if(!(Yr(r)&&Yr(t)))return 0;let s=0,o=Object.keys(t),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(T(t[n])||e&&e.includes(n)))if(Yr(r[n])&&Yr(t[n]))s+=lt(r[n],t[n],e,i);else{if(i&&i.includes(t[n]))continue;r[n]!==t[n]&&(r[n]=t[n],s+=1)}return s},lo=r=>Y(r)?document.getElementById(r):r,Zl=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),eh=()=>Zl.format(new Date);function ze(r,{keysToInclude:t,keysToExclude:e}){try{if(de(r))return`[${r.map(n=>ze(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!He(r)||!de(t)&&!de(e))return JSON.stringify(r);let i={},s=new Set(t),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(i[n]=He(r[n])||de(r[n])?JSON.parse(ze(r[n],{keysToExclude:e,keysToInclude:t})):r[n])}),JSON.stringify(i)}catch(i){return"{}"}}function $n(r,t=!1){let e=[];return Object.keys(r).forEach(i=>{t===r[i]&&e.push(i)}),ze(r,{keysToInclude:e})}function ho(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}function Qt({url:r,body:t,method:e,timeout:i}){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=i||5e3,s.open(e||"POST",r,!0),s.send(t)})}var th=0,ih=1,zc=2;function rh({retryFunction:r,settings:t,onError:e,onRetrying:i,onRetryFailed:s,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:u=1e3}=t,l=0,m=-1,f=th,g=(b,L)=>p(this,null,function*(){let se=n||this;try{let Re=yield r.apply(se,a);l>0&&o&&o.call(this,l),l=0,b(Re)}catch(Re){let ui=()=>{clearTimeout(m),l=0,f=zc,L(Re)},li=()=>{f!==zc&&l<(j(c)?c():c)?(l++,f=ih,j(i)&&i.call(this,l,ui),m=window.setTimeout(()=>{m=-1,g(b,L)},j(u)?u(l):u)):(ui(),j(s)&&s.call(this,Re))};j(e)?e.call(this,{error:Re,retry:li,reject:L,retryFuncArgs:a,retryCount:l}):li()}});return new Promise(g)}}var ht=rh;var er=class{constructor(t){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=ie(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let i=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${i?`|${i}`:""}]`),A.log(t,e,T(this.userId)||qr(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var Zc=Ne(Me(),1),sh=new Zc.default,E=sh;var tr=(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))(tr||{});var _=tr;var oh="%cTRTC%c%s",nh="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ah="display: inline",ch=!(Je||Pe||En),Hn=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);!Ki&&!Br&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){E.on(_.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;((e=t==null?void 0:t.config)==null?void 0:e.logLevelToUpload)&&Xe[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),E.on(_.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),E.once(_.JOIN_FAILED,()=>{this.startUpload()}),E.on(_.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let i=this._queue[e];if(i.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:o})=>{t.map.has(s)?t.map.get(s).logs.push(i):t.map.set(s,{userId:s,sdkAppId:o,logs:[i]})});else if(Y(i.userId)&&q(i.sdkAppId)){let{userId:s,sdkAppId:o}=i;t.map.has(s)?t.map.get(s).logs.push(i):t.map.set(s,{userId:s,sdkAppId:o,logs:[i]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let s=[...t.values()];for(let o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:c}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Ps(),sdkAppId:String(a),userId:n,version:Se,log:c.map(u=>u.log).join(`
4
- `)}),a),c.forEach(u=>u.uploaded=!0)}}catch(s){}let i=e.filter(s=>!s.uploaded);i.length>0&&(this._queue=i.concat(this._queue))})}uploadLogWithRetry(t,e){return ht({retryFunction:()=>Qt({url:Ii(e,fi.LOG),body:t,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:i})=>{i()}})()}getPrefix(t){let e=new Date;e.setTime(Rr());let i=String(e.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}] <${Xe[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){T(Xe[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(Y(t))return t;try{return JSON.stringify(t)}catch(e){return""}}log(t,e,i=!0,s,o){var a;if(e.unshift(this.getPrefix(t)),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,u)=>`${c} ${this.logChunkToString(u)}`.trim(),""),level:t,userId:s,sdkAppId:o,forAllJoinedClients:i}),t<this._logLevel)return;let n=((a=Xe[t])==null?void 0:a.toLowerCase())||"info";ch?console[n](oh,nh,ah,...e):console[n](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new er(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),i=e?Number(e):-1;Xe[i]&&(this._logLevelToUpload=i)}},A=new Hn;var dh=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let t=Math.random()*16|0;return(r=="x"?t:t&3|8).toString(16)})},Fn=dh;var Gn=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map);this.checkStorage()}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Ct())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(i=>{if(i.startsWith(this._prefix)){let s=JSON.parse(localStorage.getItem(i));if(s&&s.expiresIn<Date.now())return!0}return!1}).forEach(i=>localStorage.removeItem(i))}doFlush(){if(!!Ct())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){A.warn(t)}}getItem(t){if(!Ct())return null;try{let e=JSON.parse(localStorage.getItem(this.getRealKey(t)));return e&&e.expiresIn>=Date.now()?e.value:null}catch(e){A.warn(e)}}setItem(t,e){if(!!Ct())try{let i={expiresIn:Date.now()+Zs,value:e};this._queue.set(this.getRealKey(t),i)}catch(i){A.warn(i)}}deleteItem(t){if(!Ct())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return A.warn(e),!1}}clear(){if(!!Ct())try{localStorage.clear()}catch(t){A.warn(t)}}},ir=new Gn;var Dt={};gr(Dt,{HTTPS_API:()=>Eh,IS_GET_CAPABILITIES_SUPPORTED:()=>Jn,IS_GET_SETTINGS_SUPPORTED:()=>tt,IS_SEI_SUPPORTED:()=>Zt,IS_SPC_SUPPORTED:()=>es,basis:()=>gh,checkSystemRequirementsInternal:()=>Kn,decodeSupportStatus:()=>po,encodeSupportStatus:()=>sd,getBrowserInfo:()=>ph,getDisplayResolution:()=>od,isAddTransceiverSupported:()=>et,isBrowserSupported:()=>Wn,isGetReceiversSupported:()=>gi,isGetSendersSupported:()=>rr,isGetTransceiversSupported:()=>mt,isGetUserMediaSupported:()=>nd,isMediaDevicesSupported:()=>mo,isMediaSessionSupported:()=>ud,isMediaStreamTrackProcessorSupported:()=>_h,isReplaceTrackSupported:()=>Sh,isScreenCaptureApiAvailable:()=>Zr,isSelectedCandidatePair:()=>zt,isSetParametersSupported:()=>ts,isSmallStreamAPISupported:()=>cd,isSmallStreamSupported:()=>_o,isStopTransceiverSupported:()=>Ih,isTRTCSupported:()=>fh,isUnifiedPlanDefault:()=>Th,isUsedInHttpProtocol:()=>qt,isWebAudioSupported:()=>ad,isWebCodecSupported:()=>dd,isWebCodecsSupported:()=>rd,isWebRTCSupported:()=>jn,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:t,fnName:e,value:i}){return`'${r||t.name}' is a required param when calling ${e}(), received: ${i}.`},INVALID_PARAMETER_TYPE({key:r,rule:t,fnName:e,value:i}){let s=`${r||t.name}`,o="";return Array.isArray(t.type)?o=t.type.join("|"):o=t.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${oe(i)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:t,fnName:e,value:i}){return`'${r||t.name}' cannot be '${i}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:t,fnName:e,value:i}){let s=`${r||t.name}`,o=`${t.instanceOf.name||t.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${oe(i)}.`},INVALID_PARAMETER_RANGE({key:r,rule:t,fnName:e,value:i}){return`'${r||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${i}.`},INVALID_PARAMETER_MIN({key:r,rule:t,fnName:e,value:i}){return`the min value of ${r||t.name} is ${t.min}, received: ${i}.`},INVALID_PARAMETER_MAX({key:r,rule:t,fnName:e,value:i}){return`the max value of ${r||t.name} is ${t.max}, received: ${i}.`},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 t=`${r.type} failed`;return r.message&&(t=`${t}: ${r.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(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:t}){return`Failed to join room - ${r} code: ${t}`},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:t,streamType:e}){return`failed to subscribe ${t} ${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:t,fnName:e,value:i}){return`'${r||t.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(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:t})=>`'${r}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:r,fnName:t,type:e})=>`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${t}(), 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:t}){return`an error was caught on ${r}.on('${t}', 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:t,timesInSecond:e,maxSizeInSecond:i})=>`api ${t} call ${r?"size":"times"} is over ${r?`${i} bytes`:e} in a second.`,CONNECTION_ABORTED(r){return`connection aborted due to: ${r}`},API_CALL_ABORTED(r){let t;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${r.userId} ${r.streamType} stream aborted, reason: remote user ${r.userId} unpublished stream.`:t=`API aborted, reason: ${r.message}`,t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:r=>`'streamType' is required when 'userId' is not '*', calling ${r}()`};function ed(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var uh={AVOID_REPEATED_CALL(r){return`\u524D\u4E00\u4E2A ${r.name}() \u8C03\u7528\u6B63\u5728\u8FDB\u884C\u4E2D, \u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002`},INVALID_PARAMETER_REQUIRED({key:r,rule:t,fnName:e,value:i}){return`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${r||t.name}' \u662F\u5FC5\u987B\u7684\u53C2\u6570, \u6536\u5230\u7684\u503C\u4E3A: ${i}\u3002`},INVALID_PARAMETER_TYPE({key:r,rule:t,fnName:e,value:i}){let s=`${r||t.name}`,o="";return Array.isArray(t.type)?o=t.type.join("|"):o=t.type,`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${s}' \u5FC5\u987B\u662F ${o} \u7C7B\u578B, \u6536\u5230\u7684\u7C7B\u578B\u662F: ${ed(i)}\u3002`},INVALID_PARAMETER_EMPTY({key:r,rule:t,fnName:e,value:i}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${r||t.name}' \u4E0D\u80FD\u662F '${i}'\u3002`},INVALID_PARAMETER_INSTANCE({key:r,rule:t,fnName:e,value:i}){let s=`${r||t.name}`,o=`${t.instanceOf.name||t.instanceOf}`;return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${s}' \u539F\u578B\u5FC5\u987B\u662F ${o} , \u6536\u5230\u7684\u662F: ${ed(i)}\u3002`},INVALID_PARAMETER_RANGE({key:r,rule:t,fnName:e,value:i}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${r||t.name}' \u5FC5\u987B\u662F ${t.values.join("|")} \u7684\u5176\u4E2D\u4E00\u79CD, \u6536\u5230\u7684\u662F: ${i}\u3002`},API_CALL_TIMEOUT(r){return`${r.commandDesc||r.command} \u8D85\u65F6\u3002`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"\u4FE1\u4EE4\u901A\u9053\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4F60\u7684\u7F51\u7EDC\u3002",SIGNAL_CHANNEL_SETUP_FAILED(r){return`\u4FE1\u4EE4\u901A\u9053\u5EFA\u7ACB\u5931\u8D25: (\u9519\u8BEF\u7801: ${r.errorCode}, \u9519\u8BEF\u4FE1\u606F: ${r.errorMsg} })\u3002`},ERROR_MESSAGE(r){let t=`${r.type} \u5931\u8D25\u3002`;return r.message&&(t=`${t}: ${r.message}\u3002`),t},SUBSCRIPTION_TIMEOUT:"\u8FDC\u7A0B\u670D\u52A1\u5668\u4E0D\u54CD\u5E94\u8BA2\u9605\u884C\u4E3A\u3002",EXCHANGE_SDP_TIMEOUT:"\u4EA4\u6362 sdp \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",DOWNLINK_RECONNECTION_FAILED:"\u4E0B\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u52A0\u5165\u623F\u95F4\u3002",EXCHANGE_SDP_FAILED(r){return`\u4EA4\u6362 SDP \u5931\u8D25\uFF0C\u539F\u56E0 ${r.errMsg}\u3002`},REPLACE_TRACK_INVALID:"LocalStream \u53D1\u5E03\u4E4B\u540E\u624D\u53EF\u4EE5\u8C03\u7528 replaceTrack\u3002",UPDATE_OFFER_TIMEOUT:"\u66F4\u65B0 offer \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",UPLINK_RECONNECTION_FAILED:"\u4E0A\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u63A8\u6D41\u3002",INVALID_RECORDID:"recordId \u5FC5\u987B\u662F\u6570\u5B57\u3002",INVALID_PURE_AUDIO:"pureAudioPushMode \u5FC5\u987B\u662F\u6570\u5B571\u62162\u3002",INVALID_STREAMID:"streamId \u5FC5\u987B\u662F 64 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId \u5FC5\u987B\u662F\u5305\u542B (a-zA-Z)\u3001(0-9)\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\uFF0C64 \u4E2A\u5B57\u8282\u4EE5\u5185\uFF0C\u4E14\u4E0D\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs \u5FC5\u987B\u662F 256 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\u6587\u5B57\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_PROXY:"\u4EE3\u7406\u670D\u52A1\u5668 url \u5FC5\u987B\u4EE5\u201Cwss://\u201D\u5F00\u5934\u3002",INVALID_JOIN:"join() \u65B9\u6CD5\u4E0D\u80FD\u88AB\u91CD\u590D\u8C03\u7528\u3002",INVALID_ROOMID_STRING(r){return`\u5F53 useStringRoomId \u4E3A true \u65F6\uFF0C'${r}' \u5FC5\u987B\u662F\u5408\u6CD5\u5B57\u7B26\u4E32\u3002`},INVALID_ROOMID_INTEGER(r){return`\u5F53 useStringRoomId \u4E3A false \u65F6\uFF0C'${r}' \u5FC5\u987B\u662F\u5408\u6CD5\u6574\u6570\u5728\u533A\u95F4[1, 4294967294]\u3002`},INVALID_SIGNAL_CHANNEL:"SignalChannel \u8FD8\u672A\u521D\u59CB\u5316\u597D\u3002",JOIN_ROOM_TIMEOUT:"\u8FDB\u623F\u8D85\u65F6\u3002",JOIN_ROOM_FAILED(r){return`\u8FDB\u623F\u5931\u8D25\uFF0C\u539F\u56E0\uFF1A${r.error}\u3002`},REJOIN_ROOM_FAILED(r){return`\u91CD\u8FDB\u623F: ${r.roomId} \u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u72B6\u51B5\u3002`},INVALID_LEAVE:"\u8BF7\u5728\u8C03\u7528 destroy() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 leave()\u3002",INVALID_PUBLISH:"\u8BF7\u5728\u8C03\u7528 publish() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 join()\u3002",INVALID_UNPUBLISH:"\u8FD8\u6CA1\u6709\u88AB publish\u3002",INVALID_AUDIENCE:"\u5728\u89C2\u4F17\u6A21\u5F0F\u4E0B\u4E0D\u5141\u8BB8\u8C03\u7528 publish()\uFF0C\u8BF7\u5148\u5207\u6362\u6210\u4E3B\u64AD\u6A21\u5F0F\u3002",INVALID_INITIALIZE:"\u65E0\u6CD5\u53D1\u5E03 stream\uFF0C\u539F\u56E0\uFF1AlocalStream \u672A\u521D\u59CB\u5316\u3001\u6B63\u5728\u5207\u6362\u8BBE\u5907\u3001\u5DF2\u7ECF\u8C03\u7528 localStream.close() \u5173\u95ED\u91C7\u96C6",INVALID_DUPLICATE_PUBLISHING:"\u91CD\u590D\u53D1\u5E03\uFF0C\u8BF7\u5148 unpublish \u4E4B\u540E\uFF0C\u518D\u91CD\u65B0 publish\u3002",INVALID_SUBSCRIBE_UNDEFINED:"stream \u53C2\u6570\u662F undefined \u6216\u8005 null\u3002",INVALID_SUBSCRIBE_LOCAL:"stream \u53C2\u6570\u4E0D\u80FD\u4E3A\u672C\u5730\u6D41\u3002",INVALID_REMOTE_STREAM:"remoteStream \u4E0D\u5B58\u5728\uFF0C\u5DF2\u88AB\u8FDC\u7AEF client \u53D6\u6D88\u53D1\u5E03\u3002",SUBSCRIBE_FAILED(r){let t="\u8BA2\u9605\u6D41\u5931\u8D25\uFF0C\u539F\u56E0: ";return r.message.includes("REMOTE_STREAM_NOT_EXIST")?t+="\u8FDC\u7AEF\u7528\u6237\u5DF2\u53D6\u6D88\u63A8\u6D41\uFF0C\u65E0\u6CD5\u8BA2\u9605\u8BE5\u8FDC\u7AEF\u6D41\u3002":t+=`${r.message}\u3002`,t},INVALID_ROLE:"\u53EA\u6709\u76F4\u64AD\u6A21\u5F0F\u624D\u53EF\u4EE5\u8FDB\u884C\u89D2\u8272\u5207\u6362\u3002",INVALID_PARAMETER_SWITCH_ROLE:"role \u53EA\u80FD\u8BBE\u7F6E\u4E3A anchor \u6216\u8005 audience\u3002",INVALID_OPERATION_SWITCH_ROLE:"\u8BF7\u5728\u4F7F\u7528 switchRole() \u65B9\u6CD5\u524D\u5148\u8FDB\u623F\u3002",SWITCH_ROLE_TIMEOUT:"\u5207\u6362\u89D2\u8272\u8D85\u65F6\u3002",SWITCH_ROLE_FAILED(r){return`\u5207\u6362\u89D2\u8272\u5931\u8D25\u3002\u9519\u8BEF\u7801: ${r.code} \u9519\u8BEF\u4FE1\u606F: ${r.message}\u3002`},CLIENT_BANNED(r){return`\u60A8\u88AB\u52A8\u9000\u623F\u4E86\uFF0C\u539F\u56E0\u4E3A\uFF1A${r.reason}\u3002`},INVALID_OPERATION_START_PUBLISH_CDN:"\u8BF7\u5728\u8FDB\u623F\u524D\u6216\u8005\u8FDB\u623F\u5E76\u6210\u529F\u53D1\u5E03\u672C\u5730\u6D41\u540E\u8C03\u7528 startPublishCDNStream() \u65B9\u6CD5\u3002",INVALID_OPERATION_STOP_PUBLISH_CDN:"\u5728\u8C03\u7528 stopPublishCDNStream() \u65B9\u6CD5\u524D\u9700\u8981\u5148 startPublishCDNStream()\u3002",INVALID_STREAM_ID(r){return`'${r}' \u53EA\u80FD\u7531\u5927\u5C0F\u5199\u5B57\u6BCD\uFF08a-zA-z\uFF09, \u6570\u5B57\uFF080-9\uFF09, \u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF\u7EC4\u6210`},START_PUBLISH_CDN_FAILED(r){return`startPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${r.message}\u3002`},STOP_PUBLISH_CDN_FAILED(r){return`stopPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${r.message}\u3002`},START_MIX_TRANSCODE:"\u8C03\u7528 startMixTranscode() \u65B9\u6CD5\u524D\u9700\u8981\u5148\u8C03\u7528 join()\u3002",STOP_MIX_TRANSCODE:"\u8C03\u7528 stopMixTranscode \u4E4B\u524D\u9700\u8981\u8C03\u7528 startMixTranscode\u3002",INVALID_AUDIO_VOLUME:"interval \u5FC5\u987B\u662F\u6570\u5B57\u3002",ENABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5F00\u542F\u5C0F\u6D41\u3002",DISABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5173\u95ED\u5C0F\u6D41\u3002",NOT_SUPPORTED_SMALL_STREAM:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5F00\u542F\u5C0F\u6D41\u3002",INVALID_SMALL_STREAM_PROFILE:"\u5C0F\u6D41\u53C2\u6570\u4E0D\u5408\u6CD5\u3002",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream \u4E0D\u5408\u6CD5\u3002",REMOTE_NOT_PUBLISH_SMALL_STREAM:"\u8FDC\u7AEF\u7528\u6237\u6CA1\u6709\u53D1\u5E03\u5C0F\u6D41\u3002",INVALID_SWITCH_DEVICE:"\u5F53\u524D\u7684\u6D41\u4E0D\u53EF\u4EE5\u8C03\u7528 switchDevice\u3002",INVALID_SWITCH_DEVICE_PUBLISHING:"\u53D1\u5E03\u672C\u5730\u6D41\u65F6\u4E0D\u80FD\u5207\u6362\u8BBE\u5907\u3002",INVALID_REPLACE_TRACK:"client.publish \u63A5\u53E3\u5C1A\u672A\u8C03\u7528\u5B8C\u6210\uFF0C\u8BF7\u7B49\u5176\u8C03\u7528\u5B8C\u6210\u540E\u518D\u8C03\u7528 replaceTrack \u63A5\u53E3\u3002",INVALID_INITIALIZE_LOCAL_STREAM:"\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_REPETITIVE:"\u524D\u4E00\u4E2A addTrack \u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002",INVALID_ADD_TRACK_REMOVING:"track \u5728\u79FB\u52A8\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_ADD_TRACK_PUBLISHING:"\u5728\u53D1\u5E03\u672C\u5730\u6D41\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_STREAM_INITIALIZED:"\u60A8\u7684\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_NUMBER:"\u4E00\u6761\u6D41\u6700\u591A\u6709\u4E00\u4E2A\u97F3\u9891\u8F68\u9053\u548C\u4E00\u4E2A\u89C6\u9891\u8F68\u9053\u3002",INVALID_REMOVE_AUDIO_TRACK:"remove audio track \u662F\u4E0D\u5141\u8BB8\u7684\u3002",INVALID_REMOVE_AUDIO_ADDING:"\u5F53\u4E00\u4E2A track \u88AB addTrack \u7684\u65F6\u5019\u4E0D\u80FD\u5BF9\u6D41\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_AUDIO_ON:"\u524D\u4E00\u6B21\u8C03\u7528\u7684 removeTrack \u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_PUBLISHING:"\u53D1\u5E03\u6D41\u7684\u8FC7\u7A0B\u4E2D\u4E0D\u80FD\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"\u88AB remove \u7684 track \u6CA1\u6709\u88AB\u53D1\u5E03\u3002",INVALID_REMOVE_TRACK_NUMBER:"\u4E0D\u652F\u6301\u79FB\u9664\u552F\u4E00\u7684\u89C6\u9891\u8F68\u9053\uFF0C\u8BF7\u4F7F\u7528 replaceTrack \u6216\u8005 muteVideo \u65B9\u6CD5\u3002",INVALID_REPLACE_TRACK_NO_TRACK(r){return`LocalStream \u6CA1\u6709 ${r.kind} track\uFF0C\u65E0\u6CD5\u8FDB\u884C\u66FF\u6362\u3002`},START_MIX_TRANSCODE_FAILED(r){return`startMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${r.message}\u3002`},STOP_MIX_TRANSCODE_FAILED(r){return`stopMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${r.message}\u3002`},MIX_TRANSCODE_NOT_STARTED:"\u8FD8\u6CA1\u6709\u5F00\u59CB mixTranscode\u3002",CANNOT_LESS_THAN_ZERO({key:r,rule:t,fnName:e}){return`'\u5F53\u8C03\u7528 ${e}() \u51FD\u6570\u65F6\uFF0C\u8981\u6C42\u53C2\u6570 ${r||t.name}' \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E0`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' \u5E94\u8BE5\u662F (0, 30] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' \u5E94\u8BE5\u662F [1, 8] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' \u5E94\u8BE5\u662F [32, 192] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_USER_Z_ORDER(r){return`'${r}' \u662F\u5FC5\u4F20\u7684\uFF0C\u4E14\u8981\u6C42\u4E3A [1 ,15] \u4E4B\u95F4\u7684\u6574\u6570\u3002`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' \u5FC5\u987B\u5305\u542B\u53D1\u8D77\u6DF7\u6D41\u7684\u7528\u6237\u4FE1\u606F\u3002",MIX_PARAMS_USER_STREAM:"\u8F93\u51FA\u6D41\u7684 'config.videoWidth' \u548C 'config.videoHeight' \u5E94\u8BE5\u5BB9\u7EB3\u6240\u6709\u6DF7\u5165\u6D41\u3002",INVALID_PLAY:"play() \u88AB\u91CD\u590D\u8C03\u7528\uFF0C\u8BF7\u5148 stop()\uFF0C\u7136\u540E\u518D\u91CD\u65B0\u8C03\u7528 play\u3002",INVALID_ELEMENT_ID:({key:r,fnName:t})=>`\u5728\u8C03\u7528 ${t}() \u65F6\uFF0Cdocument \u5BF9\u8C61\u4E2D\u627E\u4E0D\u5230 ${r} \u5BF9\u5E94\u7684\u5143\u7D20\uFF0C\u8BF7\u68C0\u67E5\u3002`,INVALID_ELEMENT_ID_TYPE:({key:r,type:t,fnName:e})=>`\u5728\u8C03\u7528 ${e}() \u65B9\u6CD5\u65F6\uFF0C${r} \u53C2\u6570\u5BF9\u5E94\u7684 HTML \u6807\u7B7E\u5143\u7D20\u5FC5\u987B\u662F HTMLElement \u5B9E\u4F8B\uFF0C\u60A8\u4F20\u5165\u7684\u662F\uFF1A${t}\u3002`,PLAY_FAILED:r=>`${r.media} \u64AD\u653E\u88AB\u4E2D\u65AD\uFF0C\u6D4F\u89C8\u5668\u5F02\u5E38\u539F\u56E0\uFF1A${r.error.toString()}`,INVALID_USERID:"userId \u4E0D\u80FD\u4E3A\u7A7A\u683C\u3002",INVALID_CREATE_STREAM_SOURCE:"createStream() \u751F\u6210 LocalStream \u53EF\u4EE5\u4F7F\u7528 audio & video \u6216 audioSource & videoSource \u521B\u5EFA\uFF0C\u4F46\u4E0D\u80FD\u6DF7\u5408\u4F7F\u7528\u3002",INVALID_CREATE_STREAM_SCREEN:"screen \u548C video \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_AUDIO:"audio \u548C screenAudio \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_SCREEN_AUDIO:"screen \u4E3A true \u65F6\uFF0C\u4E0D\u80FD\u8BBE\u7F6E screenAudio\u3002",NOT_SUPPORTED_HTTP:"\u7531\u4E8E\u6D4F\u89C8\u5668\u5B89\u5168\u7B56\u7565\u9650\u5236\uFF0C\u4E0D\u652F\u6301\u5728 http \u534F\u8BAE\u4E0B\u4F7F\u7528\u91C7\u96C6\u3001\u63A8\u6D41\u7B49\u80FD\u529B\uFF0C\u8BF7\u4F7F\u7528 https \u534F\u8BAE\u3002",NOT_SUPPORTED_WEBRTC:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u5B8C\u5168\u652F\u6301 WebRTC \u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_PROFILE:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 setVideoProfile \u65B9\u6CD5\u3002\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_MEDIA:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u652F\u6301 navigator.mediaDevices\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_H264ENCODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u7F16\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u63A8\u6D41\u3002",NOT_SUPPORTED_H264DECODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u89E3\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u62C9\u6D41\u3002",NOT_SUPPORTED_TRACK(r){return`\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 ${r}Track \u65B9\u6CD5\u3002`},NOT_SUPPORTED_REPLACE_TRACK:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 replaceTrack \u65B9\u6CD5\uFF0C\u8BF7\u4F7F\u7528 switchDevice \u6216\u8005 addTrack\u3002",NOT_SUPPORTED_CAPTURE:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5C4F\u5E55\u5206\u4EAB\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_AUX:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u63A8\u8F85\u6D41\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\uFF08Chrome 69+, Safari 11+, Firefox 59+\uFF09\u3002",MICROPHONE_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u9EA6\u514B\u98CE\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u9EA6\u514B\u98CE\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CAMERA_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u6444\u50CF\u5934\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u6444\u50CF\u5934\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CATCH_HANDLER_ERROR:({name:r,event:t})=>` \u5728 ${r}.on('${t}', handler) \u4E8B\u4EF6\u4E2D\u6355\u83B7\u5230\u4E1A\u52A1\u4FA7\u9519\u8BEF\uFF0C\u8BF7\u6839\u636E\u4E0B\u8FF0\u9519\u8BEF\u4FE1\u606F\uFF0C\u68C0\u67E5\u60A8\u5728 handler \u4E2D\u7684\u4E1A\u52A1\u4EE3\u7801\u3002`,REPEAT_JOIN:r=>`\u7528\u6237 [${r}] \u6B63\u5728\u8C03\u7528\u8FDB\u623F\u63A5\u53E3\u6216\u8005\u5DF2\u7ECF\u5728\u623F\u95F4\u5185\uFF0C\u8BF7\u52FF\u91CD\u590D\u521B\u5EFA\u76F8\u540C userId \u7684 client \u8FDB\u5165\u540C\u4E00\u4E2A\u623F\u95F4\u3002`,CLIENT_DESTROYED:({funName:r})=>`client \u5DF2\u7ECF\u88AB\u9500\u6BC1\uFF0C\u8C03\u7528 ${r}() \u65B9\u6CD5\u5931\u8D25\u3002`,API_CALL_ABORTED(r){let t;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`\u4E2D\u65AD\u8BA2\u9605\u7528\u6237 ${r.userId} \u7684 ${r.streamType} stream, \u539F\u56E0: \u5728\u60A8\u8BA2\u9605\u8FC7\u7A0B\u4E2D\uFF0C\u8FDC\u7AEF\u7528\u6237 ${r.userId} \u53D6\u6D88\u4E86\u63A8\u6D41\uFF0C\u60A8\u53EF\u4EE5\u5728\u4E0B\u6B21\u8FDC\u7AEF\u63A8\u6D41\u65F6\u518D\u8FDB\u884C\u8BA2\u9605\u3002`:t=`\u4E2D\u65AD\u63A5\u53E3\u8C03\u7528, \u539F\u56E0: ${r.message}\u3002`,t},SEI_BEFORE_PUBLISH:"\u5F53\u524D client \u6CA1\u6709\u63A8 localStream(\u4E3B\u6D41\uFF0C\u975E\u5C4F\u5E55\u5206\u4EAB\u6D41)\uFF0C\u65E0\u6CD5\u8C03\u7528 client.sendSEIMessage() \u63A5\u53E3\u3002"},lh={INVALID_USER_DEFINE_RECORDID:"TRTC.html#createClient",INVALID_PROXY:"Client.html#setProxyServer",INVALID_JOIN:"Client.html#join",INVALID_ROOMID_STRING:"Client.html#join",INVALID_ROOMID_INTEGER:"Client.html#join",INVALID_PUBLISH:"Client.html#publish",INVALID_UNPUBLISH:"Client.html#unpublish",INVALID_AUDIENCE:"Client.html#switchRole",INVALID_INITIALIZE:"Client.html#publish",INVALID_DUPLICATE_PUBLISHING:"Client.html#publish",INVALID_SUBSCRIBE_UNDEFINED:"Client.html#subscribe",INVALID_SUBSCRIBE_LOCAL:"Client.html#subscribe",INVALID_REMOTE_STREAM:"Client.html#subscribe",INVALID_ROLE:"Client.html#switchRole",INVALID_PARAMETER_SWITCH_ROLE:"Client.html#switchRole",INVALID_OPERATION_SWITCH_ROLE:"Client.html#switchRole",CLIENT_BANNED:"module-ClientEvent.html#.CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"Client.html#startPublishCDNStream",INVALID_OPERATION_STOP_PUBLISH_CDN:"Client.html#stopPublishCDNStream",START_MIX_TRANSCODE:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE:"Client.html#stopMixTranscode",INVALID_AUDIO_VOLUME:"Client.html#enableAudioVolumeEvaluation",ENABLE_SMALL_STREAM_PUBLISHED:"Client.html#enableSmallStream",DISABLE_SMALL_STREAM_PUBLISHED:"Client.html#disableSmallStream",NOT_SUPPORTED_SMALL_STREAM:"tutorial-27-advanced-small-stream.html#h2-4",INVALID_SMALL_STREAM_PROFILE:"Client.html#setSmallStreamProfile",REMOTE_NOT_PUBLISH_SMALL_STREAM:"Client.html#setRemoteVideoStreamType",INVALID_SWITCH_DEVICE:"LocalStream.html#switchDevice",INVALID_SWITCH_DEVICE_PUBLISHING:"LocalStream.html#switchDevice",INVALID_REPLACE_TRACK:"LocalStream.html#replaceTrack",INVALID_INITIALIZE_LOCAL_STREAM:"LocalStream.html#replaceTrack",INVALID_ADD_TRACK_REPETITIVE:"LocalStream.html#addTrack",INVALID_ADD_TRACK_REMOVING:"LocalStream.html#addTrack",INVALID_ADD_TRACK_PUBLISHING:"LocalStream.html#addTrack",INVALID_STREAM_INITIALIZED:"LocalStream.html#addTrack",INVALID_ADD_TRACK_NUMBER:"LocalStream.html#addTrack",INVALID_REMOVE_AUDIO_TRACK:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ADDING:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ON:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NUMBER:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHED:"LocalStream.html#removeTrack",START_MIX_TRANSCODE_TIMEOUT:"Client.html#startMixTranscode",START_MIX_TRANSCODE_FAILED:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE_FAILED:"Client.html#stopMixTranscode",MIX_TRANSCODE_NOT_STARTED:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_FRAMERATE:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_GOP:"Client.html#startMixTranscode",MIX_PARAMS_AUDIO_BITRATE:"Client.html#startMixTranscode",MIX_PARAMS_USER_Z_ORDER:"Client.html#startMixTranscode",MIX_PARAMS_NOT_SELF:"Client.html#startMixTranscode",MIX_PARAMS_USER_STREAM:"Client.html#startMixTranscode",INVALID_PLAY:"Stream.html#play",PLAY_FAILED:"Stream.html#play",INVALID_USERID:"TRTC.html#createClient",INVALID_CREATE_STREAM_SOURCE:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN:"TRTC.html#createStream",INVALID_CREATE_STREAM_AUDIO:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN_AUDIO:"TRTC.html#createStream",NOT_SUPPORTED_HTTP:"tutorial-05-info-browser.html#h2-2",NOT_SUPPORTED_WEBRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_TRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_PROFILE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_MEDIA:"tutorial-05-info-browser.html",NOT_SUPPORTED_H264ENCODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_H264DECODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_TRACK:"LocalStream.html#addTrack",NOT_SUPPORTED_REPLACE_TRACK:"LocalStream.html#replaceTrack",NOT_SUPPORTED_CAPTURE:"tutorial-05-info-browser.html",MICROPHONE_NOT_FOUND:"TRTC.html#createStream",CAMERA_NOT_FOUND:"TRTC.html#createStream",SUBSCRIBE_FAILED:"Client.html#subscribe",API_CALL_ABORTED(r){let t;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?t="Client.html#subscribe":t="module-ErrorCode.html#.API_CALL_ABORTED",t}};typeof window!="undefined"&&(window.TRTC_ERROR_INFO=uh,window.TRTC_ERROR_LINK=lh);var td=(r,t)=>t?`${ct}/${r}/${t}`:`${ct}/${r}/index.html`;var hh=()=>{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(bn);if(r){r=JSON.parse(r);let t=document.createElement("script");t.type="text/javascript",t.text=r.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,i=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:i}}return{}};function D(r){let{key:t,data:e,link:i,addDocLink:s=!0}=r,o="",n="",a="";j(me[t])?o=me[t](e):Y(me[t])&&(o=me[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:u}=hh();i?a=`${i.className}.html#${i.fnName}`:u&&u[t]&&(j(u[t])?a=u[t](e):Y(u[t])&&(a=u[t]));let l=o;return ut()&&(c&&c[t]&&(j(c[t])?n=c[t](e):Y(c[t])&&(n=c[t])),n&&(s?l=`${n}
3
+ `}});var dc=Ar(Ft=>{var Mi=Cu(),Im=yu();Ft.write=Im;Ft.parse=Mi.parse;Ft.parseFmtpConfig=Mi.parseFmtpConfig;Ft.parseParams=Mi.parseParams;Ft.parsePayloads=Mi.parsePayloads;Ft.parseRemoteCandidates=Mi.parseRemoteCandidates;Ft.parseImageAttributes=Mi.parseImageAttributes;Ft.parseSimulcastStreamList=Mi.parseSimulcastStreamList});import pk from"webrtc-adapter";var hu=ye(Le());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}`)},Nr=function(){return new Date().getTime()+hn},Ls=function(){let r=new Date;return r.setTime(Nr()),r.toLocaleString()};var Re={};Rr(Re,{bytes2ms:()=>jl,copyProperties:()=>Jl,deepMerge:()=>lt,env:()=>Kt,fibonacci:()=>tr,formatedTime:()=>th,getConstructorName:()=>uo,getContainerFromElement:()=>lo,getEnv:()=>Wl,getInternalVersion:()=>ql,getLoggerUrl:()=>Ii,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:()=>Ai,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={};Rr(Kt,{ANDROID_VERSION:()=>_n,CHROME_MAJOR_VERSION:()=>pi,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:()=>Ie,IS_ANDROID_WEBVIEW:()=>Sl,IS_ANY_SAFARI:()=>Sn,IS_CHROME:()=>Ki,IS_CHROME_OS:()=>Hc,IS_CHROMIUM_BASE:()=>mi,IS_EDG:()=>Fi,IS_EDGE:()=>$i,IS_ELECTRON:()=>Tl,IS_FIREFOX:()=>X,IS_HEADLESS_CHROME:()=>gn,IS_HUAWEI:()=>gl,IS_HUAWEIBROWSER:()=>Pr,IS_IE:()=>Fc,IS_IE8:()=>_l,IS_IOS:()=>Je,IS_IOS_13_OR_14:()=>Il,IS_IOS_15_1:()=>Ur,IS_IPAD:()=>Bi,IS_IPADQQB:()=>kr,IS_IPAD_PRO:()=>pn,IS_IPHONE:()=>Gt,IS_IPOD:()=>$c,IS_LINUX:()=>Mr,IS_LOCAL:()=>Ye,IS_MAC:()=>je,IS_MACQQB:()=>vr,IS_MIBROWSER:()=>Lr,IS_MQQB:()=>Wi,IS_NATIVE_ANDROID:()=>pl,IS_OLD_ANDROID:()=>ml,IS_OPPOBROWSER:()=>wr,IS_SAFARI:()=>$e,IS_SAFARI_15_1:()=>An,IS_SAMSUNGBROWSER:()=>xr,IS_SOGOU:()=>br,IS_SOGOUM:()=>yr,IS_TBS:()=>nt,IS_UCBROWSER:()=>Tn,IS_VIVOBROWSER:()=>Vr,IS_WECHAT:()=>Hi,IS_WIN:()=>Rt,IS_WQQB:()=>Dr,IS_WX:()=>El,IS_X5MQQB:()=>Gi,IS_XWEB:()=>Or,MACQQB_VERSION:()=>Gs,MI_VERSION:()=>Ks,MQQB_VERSION:()=>Ui,OPPO_VERSION:()=>Ys,SAFARI_VERSION:()=>Ji,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,Bi=H("iPad"),pn=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&H("Macintosh"),Gt=H("iPhone")&&!Bi,$c=H("iPod"),Je=Gt||Bi||$c||pn,Ie=H("Android"),_n=function(){if(Ie){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=Ie&&H("webkit")&&_n<2.3,pl=Ie&&_n<5&&hl<537,X=H("Firefox"),Ps=le("Firefox"),fn=mn("Firefox"),$i=H("Edge"),xs=le("Edge"),Fi=H("Edg"),ws=le("Edg"),En=mn("Edg"),yr=H("SogouMobileBrowser"),Vs=le("SogouMobileBrowser"),br=H("MetaSr\\s"),Us=le("MetaSr\\s"),nt=H("TBS"),Bs=le("TBS"),Or=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}(),Hi=H("(micromessenger|webbrowser)"),Fs=le("MicroMessenger"),Gi=!nt&&H("MQQBrowser")&&H("COVC"),Wi=!nt&&H("MQQBrowser")&&!H("COVC"),Ui=Wi||Gi?le("MQQBrowser"):"",Dr=!nt&&H(" QQBrowser"),Hs=le(" QQBrowser"),vr=!nt&&H("QQBrowserLite"),Gs=le("QQBrowserLite"),kr=!nt&&H("MQBHD"),Ws=le("MQBHD"),Rt=H("Windows"),je=!Je&&H("MAC OS X"),Mr=!Ie&&H("Linux"),Hc=H("CrOS"),El=H("MicroMessenger"),Tn=H("UCBrowser"),Tl=H("Electron"),Lr=H("MiuiBrowser"),Ks=le("MiuiBrowser"),Pr=H("HuaweiBrowser"),gl=H("Huawei"),Js=le("HuaweiBrowser"),xr=H("SamsungBrowser"),js=le("SamsungBrowser"),wr=H("HeyTapBrowser"),Ys=le("HeyTapBrowser"),Vr=H("VivoBrowser"),Qs=le("VivoBrowser"),at=()=>mn("Chrome"),mi=H("Chrome"),Ki=!$i&&!br&&!yr&&!nt&&!Or&&!Fi&&!Dr&&!Lr&&!Pr&&!xr&&!wr&&!Vr&&mi,gn=H("HeadlessChrome"),pi=at(),qs=le("Chrome"),$e=!mi&&!Wi&&!Gi&&!vr&&!kr&&H("Safari"),Sn=$e||Je,Ji=le("Version"),Sl=/Android.*(wv|.0.0.0)/.test(Ke),Wt=(()=>{if(pn)return Ji;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=Ji==="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]],[Fi,["Edg",ws]],[Ki,["Chrome",qs]],[$e,["Safari",Ji]],[nt,["TBS",Bs]],[Or,["XWEB",$s]],[Hi&&Gt,["WeChat",Fs]],[Dr,["QQ(Win)",Hs]],[Wi,["QQ(Mobile)",Ui]],[Gi,["QQ(Mobile X5)",Ui]],[vr,["QQ(Mac)",Gs]],[kr,["QQ(iPad)",Ws]],[Lr,["MI",Ks]],[Pr,["HW",Js]],[xr,["Samsung",js]],[wr,["OPPO",Ys]],[Vr,["VIVO",Qs]],[$i,["EDGE",xs]],[yr,["SogouMobile",Vs]],[br,["Sogou",Us]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var be=null;function Br(){return p(this,null,function*(){if(be)return be;if(!navigator.userAgentData||!j(navigator.userAgentData.getHighEntropyValues))return null;try{return be=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),be}catch(r){return null}})}var Bc=new Map([[Ie,"Android"],[Je,"iOS"],[Rt,"Windows"],[je,"MacOS"],[Mr,"Linux"],[Hc,"ChromeOS"]]),Xs=function(){return Bc.get(!0)?Bc.get(!0):be?be.platform:"unknown"},Rn=()=>{let r=Xs();return r+=`/${ot.name}/${$e?ot.version:ot.version.split(".")[0]}`,be!=null&&be.platformVersion&&(r+=`/${be.platformVersion}`),be!=null&&be.architecture&&(r+=`/${be.architecture}`),r};var Bn={};Rr(Bn,{AUDIO_MUTE_BIT:()=>ro,AUDIO_STAT_BIT:()=>Qi,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:()=>Si,IS_WORKER:()=>ji,IS_WORKLET:()=>$r,KIBANA_EVENT:()=>Oe,LOCAL_STREAM_PUBLISH_STATE:()=>Jc,LOGGER_CMD_TYPE:()=>Ei,LOGGER_DOMAIN:()=>bn,LOGGER_DOMAIN_OVERSEA:()=>On,LOG_LEVEL:()=>Qe,LOG_LEVEL_NAME:()=>Fl,MAIN_STREAM_MSID:()=>Gr,MICROPHONE_COMMUNICATIONS:()=>$l,MICROPHONE_DEFAULT:()=>gi,NAME:()=>h,NETWORK_TYPE:()=>Jt,NOT_SUPPORTED_H264:()=>Ti,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:()=>Xi,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:()=>zi,SYNC_USER_LIST_INTERVAL:()=>Pl,Scene:()=>bt,Switch:()=>Wc,THIRD_HOST:()=>yn,TIMEOUT:()=>er,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:()=>Yi,audioProfileMap:()=>eo,getRetryCount:()=>Ot,getScriptDir:()=>Al,innerVersion:()=>_i,loggerProxy:()=>Fr,screenProfileMap:()=>to,setLoggerProxy:()=>fi,setRetryCount:()=>Pn,setVersion:()=>Cn,version:()=>Ae,videoProfileMap:()=>yt});var _i="4.15.00.1600",Ae="5.0.0";function Cn(r){Ae=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));_i=`${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="",fi=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",Ei={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||{}),Yi=1,vn=2,Hr=4,Qi=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,Oe={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",Ti=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,Xi={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,gi="default",Jr=gi,$l="communications",Fl=Object.keys(Qe),Un=["normal leave","timeout leave","kick","role change"],zi=10,Zi=2e3,dt="ric",jr="raf",Si="interval",er="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,Ii=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 Ie?4:Gt?2:Bi?3:je?12:Rt?5:Mr?13:1}function Qc(){return Ie?"Android":Gt?"iPhone":Bi?"iPad":je?"Mac":Rt?"Windows":Mr?"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:_i,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 tr(r,i=1,e=1){return r<=1?e:tr(r-1,e,i+e)}function He(r){return r>8?30*1e3:tr(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",Ai=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&Qi),hasVideo:!!(r&Yi),hasAuxiliary:!!(r&Hr),hasSmall:!!(r&vn),audioMuted:!!(r&ro),videoMuted:!!(r&so),audioAvailable:!!(r&Qi)&&!(r&ro),videoAvailable:!!(r&Yi)&&!(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)||Ai(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 ir=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=ye(Le(),1),oh=new ed.default,E=oh;var rr=(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))(rr||{});var _=rr;var nh="%cTRTC%c%s",ah="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ch="display: inline",dh=!(Je||Ie||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:Ae,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:Ii(e,Ei.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(Nr());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 ir(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)}}},sr=new Kn;var Dt={};Rr(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:()=>Ri,isGetSendersSupported:()=>or,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
5
  \u8BF7\u67E5\u770B\u6587\u6863: ${td("zh-cn",a)}
6
6
 
7
7
  `:l=`${n}
8
8
 
9
9
  `,l+=o)),s&&(l+=`
10
10
  Refer to: ${td("en",a)}
11
- `),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}},mh=new Map([[Q,["Firefox",ks]],[Bi,["Edg",ws]],[Gi,["Chrome",Qs]],[$e,["Safari",Wi]],[nt,["TBS",Bs]],[yr,["XWEB",$s]],[$i&&Gt,["WeChat",Hs]],[br,["QQ(Win)",Fs]],[Fi,["QQ(Mobile)",wi]],[Hi,["QQ(Mobile X5)",wi]],[Or,["QQ(Mac)",Gs]],[Dr,["QQ(iPad)",Ws]],[Lr,["MI",Ks]],[Mr,["HW",Js]],[Pr,["Samsung",js]],[kr,["OPPO",Ys]],[xr,["VIVO",Xs]],[Ui,["EDGE",xs]],[Cr,["SogouMobile",Vs]],[Nr,["Sogou",Us]]]);function ph(){let r=mh.get(!0),t=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:t,browserVersion:e}}var Wn=function(){return!(fn||Ui||Bi&&_n<80||Q&&pn<56)},rd=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},mo=function(){if(!navigator.mediaDevices)return qt()||A.error(me.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(t=>t in navigator.mediaDevices).length===r.length},id=!1;function qt(){return location.protocol==="http:"&&!Ye?(id||A.error(D({key:O.NOT_SUPPORTED_HTTP})),id=!0,!0):!1}var _h=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,t=!1,e=!1;try{let i=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return i.addTrack(o.getVideoTracks()[0],o),r=yield i.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),i.close(),z.detail.isH264EncodeSupported=t,z.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:z.detail.isH264EncodeSupported,isVp8EncodeSupported:z.detail.isVp8EncodeSupported}}catch(i){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,t=!1,e=!1;try{let i=new RTCPeerConnection;return r=yield i.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),i.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(i){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Kn=function(){return p(this,null,function*(){if(z.result)return z;let r=Wn(),t=jn(),e=rd(),i=mo(),{isH264EncodeSupported:s,isVp8EncodeSupported:o}=yield sd(),{isH264DecodeSupported:n,isVp8DecodeSupported:a}=yield po();return z.result=r&&t&&i&&(s||o)&&(n||a),z.detail.isBrowserSupported=r,z.detail.isWebRTCSupported=t,z.detail.isWebCodecsSupported=e,z.detail.isMediaDevicesSupported=i,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} ${$n(z.detail,!1)}`),z})},fh=function(){return z.result},Zr=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Eh=(r,t,e)=>{location.protocol==="http:"&&!Ye&&(r[t]=()=>{throw new C({code:I.INVALID_OPERATION,message:me.NOT_SUPPORTED_HTTP})})},zt=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(ie(r.selected)&&!r.selected):!1};function od(){let r="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${t} * ${e}`}return r}function nd(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ad(){let r={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){r.isSupported=!0;break}return r.isSupported}function cd(){return"captureStream"in HTMLCanvasElement.prototype}function _o(){return $i||Je||mi&&mi<63?!1:!!(Wn()&&cd())}var Th=function(){if(T(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,t=!1;try{r=new RTCPeerConnection({sdpSemantics:jt}),r.addTransceiver(h.AUDIO),t=!0}catch(e){}return r==null||r.close(),t};function gi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function rr(){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()||wr&&mi<74))();function Ih(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Sh(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function ts(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&rr()}var tt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Jn=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Zt="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&at()>=86,jn=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t 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 gh(){let r={browser:`${ot.name}/${ot.version}`,os:qs(),displayResolution:od(),isScreenShareSupported:Zr(),isWebRTCSupported:jn(),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"),zp=Symbol("abortCtrl"),Yn=Symbol("cacheResult"),Ai=class{constructor(t,e,i){this.oldState=t,this.newState=e,this.action=i,this.aborted=!1}abort(t){this.aborted=!0,ss.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},is=class extends Error{constructor(t,e,i){super(e),this.state=t,this.message=e,this.cause=i}};function Ah(r){return typeof r=="object"&&r&&"then"in r}var rs=new Map;function Z(r,t,e={}){return(i,s,o)=>{let n=e.action||s;if(!e.context){let c=rs.get(i)||[];rs.has(i)||rs.set(i,c),c.push({from:r,to:t,action:n})}let a=o.value;o.value=function(...c){let u=this;if(e.context&&(u=P.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),u.state===t)return u[Yn];u.state instanceof Ai&&u.state.action==e.abortAction&&u.state.abort(u);let l=null;if(Array.isArray(r)?r.length==0?u.state instanceof Ai&&u.state.abort(u):(typeof u.state!="string"||!r.includes(u.state))&&(l=new is(u._state,`${u.name} ${n} to ${t} failed: current state ${u._state} not in from config`)):r!==u.state&&(l=new is(u._state,`${u.name} ${n} to ${t} 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 Ai(m,t,n);ss.call(u,f);let g=L=>{var se;return u[Yn]=L,f.aborted||(ss.call(u,t),(se=e.success)===null||se===void 0||se.call(this,u[Yn])),L},b=L=>{let se=L instanceof Error?L.message:String(L);if(ss.call(u,m,L),e.fail)e.fail.call(this,new is(u._state,`action '${n}' failed :${se}`,L instanceof Error?L:new Error(se)));else{if(e.ignoreError)return L;throw L}};try{let L=a.apply(this,c);return Ah(L)?L.then(g).catch(b):g(L)}catch(L){b(L)}}}}var Rh=(()=>typeof window!="undefined"&&window.__AFSM__?(e,i)=>{window.dispatchEvent(new CustomEvent(e,{detail:i}))}:typeof importScripts!="undefined"?(e,i)=>{postMessage({type:e,payload:i})}:()=>{})();function ss(r,t){let e=this._state;this._state=r;let i=r.toString();r&&this.emit(i,e),this.emit(P.STATECHANGED,r,e,t),this.updateDevTools({value:r,old:e,err:t instanceof Error?t.message:String(t)})}var P=class extends md.default{constructor(t,e,i){super(),this.name=t,this.groupName=e,this._state=P.INIT,t||(t=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=i[hd];s?this.name=s.name+"-"+s.count++:i[hd]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=rs.get(t)||[],i=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(t);rs.has(a)&&(a.stateDiagram.forEach(u=>i.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"),i.add(`${u} --> ${m}ing : ${m}`),i.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),i.add(`${m}ing --> ${u} : ${m} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{i.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),n.forEach(m=>{m!==u&&i.add(`${m} --> ${l}ing : ${l}`)})});let c=[...i];return Object.defineProperties(t,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(t){let e;return typeof t=="string"?(e=P.instances.get(t),e||P.instances.set(t,e=new P(t,void 0,Object.create(P.prototype)))):(e=P.instances2.get(t),e||P.instances2.set(t,e=new P(t.constructor.name,void 0,Object.create(P.prototype)))),e}static getState(t){var e;return(e=P.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){Rh(P.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){ss.call(this,t)}};P.STATECHANGED="stateChanged";P.UPDATEAFSM="updateAFSM";P.INIT="[*]";P.ON="on";P.OFF="off";P.instances=new Map;P.instances2=new WeakMap;var pd=(window==null?void 0:window.requestIdleCallback)||function(r){let t=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},Ch=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Nh=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),os=class{static generateTaskID(){return this.currentTaskID++}static run(t=zi,e,i){t===jr?i=N({delay:2e3,count:0,backgroundTask:!0},i):t===dt?i=N({delay:1e4,count:0},i):t===Jr?i=N({fps:60,delay:16.6,count:0,backgroundTask:!0},i):i=N({delay:2e3,count:0,backgroundTask:!0},i),Si(e)&&(i=N(N({},i),e)),j(t)&&(e=t,t=zi);let s=N({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},i);return this.taskMap.set(s.taskID,s),this[t](s),s.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,this.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){t.delay=(1e3/t.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
11
+ `),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]],[Fi,["Edg",ws]],[Ki,["Chrome",qs]],[$e,["Safari",Ji]],[nt,["TBS",Bs]],[Or,["XWEB",$s]],[Hi&&Gt,["WeChat",Fs]],[Dr,["QQ(Win)",Hs]],[Wi,["QQ(Mobile)",Ui]],[Gi,["QQ(Mobile X5)",Ui]],[vr,["QQ(Mac)",Gs]],[kr,["QQ(iPad)",Ws]],[Lr,["MI",Ks]],[Pr,["HW",Js]],[xr,["Samsung",js]],[wr,["OPPO",Ys]],[Vr,["VIVO",Qs]],[$i,["EDGE",xs]],[yr,["SogouMobile",Vs]],[br,["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||$i||Fi&&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 Hi||Je||pi&&pi<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 Ri(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function or(){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()||mi&&pi<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&&or()}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=ye(Le(),1);var hd=Symbol("instance"),Qp=Symbol("abortCtrl"),qn=Symbol("cacheResult"),Ci=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 Ci&&u.state.action==e.abortAction&&u.state.abort(u);let l=null;if(Array.isArray(r)?r.length==0?u.state instanceof Ci&&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 Ci(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=er,e,t){i===Si?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),Ai(e)&&(t=N(N({},t),e)),j(i)&&(e=i,i=er);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([`
12
12
  let timerID = null;
13
13
  self.onmessage = function (e) {
14
14
  if (e.data === 'start') {
15
15
  timerID = setInterval(() => {
16
16
  self.postMessage('tick');
17
- }, ${t.delay});
17
+ }, ${i.delay});
18
18
  } else if (e.data === 'stop') {
19
19
  clearInterval(timerID);
20
20
  }
21
21
  };
22
- `])));e.onmessage=i=>{i.data==="tick"&&(t.callback(),t.loopCount+=1,this.isBreakLoop(t)&&e.postMessage("stop"))},t.worker=e,e.postMessage("start")}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!this.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=$(),i,s=()=>{if(i=$()-e,i>=t.delay&&(e=$()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.ricID=pd(s,{timeout:t.delay})};return t.ricID=pd(s,{timeout:t.delay})}static raf(t){t.delay=(1e3/t.fps).toFixed(2);let e=$(),i,s=()=>{if(document.hidden&&t.backgroundTask)return i=$()-e,e=$(),t.callback(),t.loopCount+=1,this.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(s,t.delay-Math.floor(i%t.delay));if(i=$()-e,i>=t.delay&&(e=$()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.rafID=requestAnimationFrame(s)};if(t.rafID=requestAnimationFrame(s),t.backgroundTask){let o=()=>{if(document.hidden){let n=$()-e;n>=t.delay?s():t.timeoutID=setTimeout(s,t.delay-n)}};document.addEventListener("visibilitychange",o),t.onVisibilitychange=o,document.hidden&&o()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:i,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(t);return a&&a.terminate(),e&&clearInterval(e),i&&clearTimeout(i),s&&Nh(s),o&&Ch(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};os.taskMap=new Map,os.currentTaskID=1;var ee=os;var s_={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:Se,env:Nt.QCLOUD,browserVersion:ot.name+ot.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:i,roomId:s}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=i,this._roomIdMap.set(i,String(s))}logSuccessEvent(t){Ye||!A.isAbleToUpload||this._configs.env===Nt.QCLOUD&&this.uploadEventToKibana(M(N({},t),{result:"success"}))}logFailedEvent(t){if(Ye||!A.isAbleToUpload)return;let{eventType:e,code:i,error:s,userId:o}=t,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:i||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||I.UNKNOWN};this._configs.env===Nt.QCLOUD&&this.uploadEventToKibana(M(N({},n),{error:s}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:i}){let s={timestamp:Ps(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Se,log:t};i&&(s.errorInfo=i.message),this.sendRequest(Ii(this._configs.sdkAppId,fi.LOG),s)}sendRequest(t,e){if(!A.isAbleToUpload){setTimeout(()=>{this.sendRequest(t,e)},1e3);return}Qt({url:t,body:JSON.stringify(e)}).catch(()=>{})}},X=new Xn;var vt="trtc_autoplay",Qn=`${vt}_mask`,sr=`${vt}_wrapper`,_d=`${vt}_header`,qn=`${vt}_content`,fo=`${vt}_action_wrapper`,zn=`${vt}_question`,Zn=`${vt}_collapse`,Eo=`${vt}_action_confirm`,fd=`${vt}_detail`,Ed="#2473E8",ta="dialog",yh=`${ta}-show`,bh=`${ta}-1`,Oh=`${ta}-2`,Td=!1,ia=()=>!!document.querySelector(`.${sr}`),Sd=`${ct}/${ut()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Id=`<br><a href='${Sd}' target='_blank'>${ut()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Dh=`${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${Id}`:`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. ${Id}`}`,ea=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 t=document.createElement("style");t.innerHTML=`.${Qn}{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;}.${Qn} div:not(.${fo}){display:block !important;}.${sr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${sr} a{color:${Ed};}.${_d}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${qn}{margin:8px 0;}.${fo}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Zn}{margin-right:auto;cursor:pointer}.${zn}{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;}.${Zn},.${Eo},.${qn},.${zn}{font-size:14px;}@media screen and (max-width:750px){.${sr}{width:80vw;}}`,document.head.appendChild(t),Td=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${Qn}"><div class='${sr}'><div class='${_d}'>${location.host}</div><div class='${qn}'>${this.content}</div><div class='${fd}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Dh}</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 i=document.createElement("div");i.className=zn,i.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
22
+ `])));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(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Ae,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:Ae,log:i};t&&(s.errorInfo=t.message),this.sendRequest(Ii(this._configs.sdkAppId,Ei.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`,nr=`${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(`.${nr}`),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;}.${nr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${nr} 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){.${nr}{width:80vw;}}`,document.head.appendChild(i),Td=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${zn}"><div class='${nr}'><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"?>
23
23
  <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">
24
24
  <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"/>
25
25
  <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"/>
26
26
  <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"/>
27
27
  </svg>
28
- `,i.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=Zn,s.innerText=`${ut()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let o=t.content.firstChild,n=o.querySelector(`.${fo}`);return n.appendChild(s),n.appendChild(i),n.appendChild(e),o}addDiaLog(){ia()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${sr}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),X.uploadEvent({log:yh}))}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 t=this._dialogNode.querySelector(`.${fd}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||X.uploadEvent({log:bh}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Sd,"_blank"),this._isQuestionClicked||X.uploadEvent({log:Oh}),this._isQuestionClicked=!0}},gd=ea;var Lt={};gr(Lt,{create:()=>Ee,remove:()=>ne});var ns=new WeakMap;function Ee(r,t){ns.has(r)||ns.set(r,[]);let e=ns.get(r),s={add:(o,n)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,o,n)),t.addEventListener(o,n)):(e.push(t.off.bind(t,o,n)),t.on(o,n)),s)};return s}function ne(r){let t=ns.get(r);t&&(t.forEach(e=>e()),ns.delete(r))}var Mt=class extends P{constructor(e,i){super(e.id,`${i}-player`);this.kind=i;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=xn,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 i=new MediaStream;i.addTrack(e),this.element.srcObject=i}}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 i=D({key:O.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),i.includes("NotAllowedError"))throw new C({code:I.PLAY_NOT_ALLOWED,message:i})}})}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&&ee.clearTask(this._interval)}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this.isPlaying?Promise.resolve():Vr?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,i){this.element&&(this.element.style.width=`${e}px`,this.element.style.height=`${i}px`)}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Ee(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);Lt==null||Lt.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&&(ee.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&&!ia()||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=ee.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}`),X.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([Z([],"PLAYING")],Mt.prototype,"handlePlaying",1),y([Z("PLAYING","PAUSED",{ignoreError:!0})],Mt.prototype,"handlePaused",1),y([Z([],"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 i=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;this.mirror&&(i+="transform: scaleX(-1);"),e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",i),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 i=e.type;if(this.mirror&&this.element){let s=this.element.style.transform;i===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):i===h.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setAttr(e){let i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}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 vh='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,ra=class{constructor(t){d(this,"context_");d(this,"blob_");this.context_=t.context,this.blob_=new Blob([vh],{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(t){A.info(`worklet addModule catch error. ${t.message}`),E.emit(_.WORKLET_LOADED_FAILED)}})}get initWorkletSuccess(){return Rd}},Cd=ra;typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Lh=0,_t=(r,t)=>{let e=new window.AudioContext(t),i=++Lh,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}-${i} context state: ${e.state}`),s()},e};var it,To,Io=0,sa=class{constructor(t){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:i}=t;this._volume=0,this._log=i,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),Un?(E.on(_.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),E.on(_.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),Io+=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=t=>{this._volume=t.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(t){X.logFailedEvent({userId:this._log.userId,eventType:be.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{let e=t.inputBuffer.getChannelData(0),i=0;for(let s=0;s<e.length;++s)i+=e[s]*e[s];this._volume=Math.sqrt(i/e.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}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),Io>0&&(Io-=1),Io===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(t){var i;let{interval:e}=t;this._interval=e,(i=this._audioWorkletNode)==null||i.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Nd=sa;var ei=null,oa=0,Ri=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 i=document.createElement(h.AUDIO);this.track&&(i.srcObject=new MediaStream([this._gainedTrack||this.track])),i.muted=this.muted,i.setAttribute("id",`audio_${this.id}`),i.setAttribute("autoplay","autoplay"),i.setAttribute("playsinline","playsinline"),this.element=i,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(Ri.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(Ri.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 i=ei.createMediaStreamSource(new MediaStream([this.track])),s=ei.createGain(),o=ei.createMediaStreamDestination();i.connect(s),s.connect(o),s.gain.value=e,this._gainNode=s,this._destination=o,this._mediaStreamSource=i,this._gainedTrack=o.stream.getAudioTracks()[0],oa+=1,this.element&&(ne(this.element),this._sourceElement=this.element,this.element.muted=!0,this.element=null),this.play()}destroyGain(){var e,i,s;!this._gainNode||(this._log.info("destroy gainNode"),(e=this._gainNode)==null||e.disconnect(),(i=this._destination)==null||i.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,oa-=1,oa===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 Ci=class extends P{constructor({userId:e,sdkAppId:i,mediaType:s,room:o,isInitPlayer:n=!0}){var a;super();d(this,"id",Fn());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:i,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,i){return p(this,null,function*(){let s=de(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!T(i.muted)&&this.setPlayerMute(i.muted),i&&!T(i.objectFit)&&(this.objectFit=i.objectFit),this.isScreen?this.mirror=!1:i&&!T(i.mirror)&&(this.mirror=i.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),i)));return}if(i&&!T(i.muted)?this.setPlayerMute(i.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),i&&!T(i.objectFit)&&(this.objectFit=i.objectFit),this.isRemote||(this.mirror=!0),this.isScreen?this.mirror=!1:i&&!T(i.mirror)&&(this.mirror=i.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(i)}`);try{this.player.setTrack(this._outputTrack),yield this.player.play(),de(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),i))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}playSubContainer(e,i){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?i&&(T(i.mirror)||a.setMirror(i.mirror),T(i.objectFit)||a.setObjectFit(i.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 Ri({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,i=>{var s;(s=this.subVideoPlayerMap)==null||s.forEach(o=>o.setTrack(i))})),this.player.on(pt.PLAYER_STATE_CHANGED,i=>{E.emit(_.PLAYER_STATE_CHANGED,N({track:this},i)),this.emit("player-state-changed",i)})}setAudioOutput(e){return p(this,null,function*(){var i;this.audioOutputDeviceId=e,yield(i=this.player)==null?void 0:i.setSinkId(e)})}setAudioVolume(e){var i;this.audioVolume=e,this.log.info(`setAudioVolume to ${e}`),(i=this.player)==null||i.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 i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this,i):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let i=this._outputTrack;e!==i&&(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 gd;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([Z([],P.INIT)],Ci.prototype,"close",1);var Mh=Object.prototype.hasOwnProperty,{toString:Uf}=Object.prototype;function Ph(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(He(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 t in r)if(Mh.call(r,t))return!1;return!0}}return!1}var kt=Ph;var bd=Ne(Me(),1);var yd=r=>t=>t.deviceId===r;var ds=class{constructor(t,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let i=t.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);e&&(i.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&&!i.find(yd(s.deviceId))){let o=`${this.kind}${this.type}Removed`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=i}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},na=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))}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=Br||Ki?null:new na;function So(){return p(this,null,function*(){return qt()||!mo()?[]:(yield navigator.mediaDevices.enumerateDevices()).map((t,e)=>{let i={kind:t.kind,deviceId:t.deviceId,groupId:t.groupId,label:t.label||`${t.kind}_${e}`};return t.deviceId.length>0&&aa.add(`${t.deviceId}_${t.kind}`),t.getCapabilities&&(i.getCapabilities=()=>t.getCapabilities()),i})})}function ke(){return ae.update().then(r=>r.audioInputs.devices)}function Ge(){return ae.update().then(r=>r.videoInputs.devices)}function or(){return p(this,null,function*(){return ae.update().then(r=>r.audioOutputs.devices)})}var aa=new Set;function Od(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let t=r.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!aa.has(i)}function Dd(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let t=r.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let i=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!aa.has(i)}function ca(r,t){return p(this,null,function*(){let i=(yield ke()).find(s=>s.deviceId===Ti);return(i==null?void 0:i.groupId)===r&&i.label===t})}function vd(o){return p(this,arguments,function*({newDeviceId:r,oldDeviceId:t,oldGroupId:e,oldLabel:i,kind:s}){return r!==t?!1:s===h.AUDIO&&r===Ti?yield ca(e,i):!0})}var kh=function(r){return p(this,null,function*(){let t=wh(r);A.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],i=[],s=["label","deviceId"];t.audio&&(e=yield ke(),A.info(`microphones: ${ze(e,{keysToInclude:s})}`)),t.video&&(i=yield Ge(),A.info(`cameras: ${ze(i,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(t);return Jn&&o.getTracks().forEach(n=>{A.info(`${n.kind} capabilities: ${ze(n.getCapabilities(),{keysToInclude:no})}`)}),o}catch(o){if(o.name==="NotFoundError"){if(r.video&&i&&i.length===0)throw new C({code:I.DEVICE_NOT_FOUND,message:D({key:O.CAMERA_NOT_FOUND})});if(r.audio&&e&&e.length===0)throw new C({code:I.DEVICE_NOT_FOUND,message:D({key:O.MICROPHONE_NOT_FOUND})})}throw new C({code:I.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint})}})},xh=ht({retryFunction:kh,settings:{retries:3,timeout:500},onError:({error:r,retry:t,reject:e,retryFuncArgs:i,retryCount:s})=>{r.name==="NotReadableError"?(i[0].video&&(i[0].maxResolution=!1,i[0].frameRate&&(i[0].frameRate=i[0].frameRate>10?10:5)),s===2&&(i[0].useTrueAsConstraint=!0),t()):e(r),i[0].microphoneId&&Ld(i[0].microphoneId,!1),i[0].cameraId&&Ld(i[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{X.logFailedEvent({eventType:be.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{X.logSuccessEvent({eventType:be.GET_USER_MEDIA_RETRY}),X.uploadEvent({log:`stat-${be.GET_USER_MEDIA_RETRY}-success-${r}`})}});function Ld(r,t){return p(this,null,function*(){let i=(t?yield Ge():yield ke()).find(s=>s.deviceId===r);i&&j(i.getCapabilities)&&A.warn(ze(i.getCapabilities(),{keysToInclude:no}))})}function wh(r){return{audio:Vh(r),video:Uh(r)}}function Vh(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let t={};return kt(r.microphoneId)||(t.deviceId=r.useExact?{exact:r.microphoneId}:r.microphoneId),q(r.channelCount)&&r.channelCount>1&&(t.channelCount=r.channelCount),ie(r.echoCancellation)&&!r.echoCancellation&&(t.echoCancellation=!1),ie(r.noiseSuppression)&&!r.noiseSuppression&&(t.noiseSuppression=!1),ie(r.autoGainControl)&&!r.autoGainControl&&(t.autoGainControl=!1),kt(t)?!0:t}function Uh(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:t=!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},t&&!Q&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},t&&!Q&&(e.height.max=r.height)),Q&&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),kt(e)?!0:e}var Md=xh;function go(r){return G((t,e)=>function(...i){return p(this,null,function*(){return yield r.apply(this,i),t.apply(this,i)})})}function Ao(r){return G((t,e)=>function(...i){return p(this,null,function*(){return r.call(this,t.apply(this,i))})})}function G(r){return function(t,e,i){return i.value=r(i.value,e),i}}var Oe=class extends Ci{constructor(e,i=!0){super({mediaType:e,isInitPlayer:i});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){Ee(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 i;e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):i=yield Md(e);let s=i.getTracks()[0];return yield this.setInputMediaStreamTrack(s),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(_.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),i}catch(i){throw E.emit(_.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:i}),this.log.error(`getUserMedia error observed ${i}`),i}})}setInputMediaStreamTrack(e){this.state===P.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let i=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),i}publish(e,i){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}),i}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(_.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.mediaType===2&&(this.mediaType=4)}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&tt){let{deviceId:e,groupId:i}=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,i&&(this.groupId=i),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<qi){setTimeout(()=>this.onTrackMuted(),qi);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<qi){setTimeout(()=>this.onTrackEnded(),qi);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;let i;return this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(this.kind==="audio"?yield ke():yield Ge()).find(n=>n.deviceId===e)&&(i=e),this.capture({deviceId:i,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 i=(us.get(e)||0)+1;if(us.set(e,i),i>=3){let s=this.kind==="video"?(yield Ge()).find(o=>!us.has(o.deviceId)):(yield ke()).find(o=>!us.has(o.deviceId));s&&(this.log.warn(`${e} capture fail ${i} 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([Z(P.INIT,"capture",{ignoreError:!0})],Oe.prototype,"setStateToCapture",1),y([Z("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(r){let t="error",e=r.cause;e.message.includes("timeout")?t="timeout":e.code===I.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e})}})],Oe.prototype,"publish",1),y([G(r=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"})})}),Z([],"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,"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:i,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:i})}switchDevice(e){return p(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Ti){if(yield ca(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(i){throw this.log.error(`switch microphone failed ${i}`),this.deviceId&&this.recapture(this.deviceId),i}}})}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 i=yield ke();i[0]?this.recapture(i[0].deviceId):ae.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){return p(this,null,function*(){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){ae.off("audioInputAdded",this.handleMicrophoneAdded,this),ae.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};var Le=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 i=()=>{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",i),this.on("publish",i)}capture({deviceId:e,facingMode:i,useExact:s=!1,customSource:o}={}){return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:s,customSource:o})}setOutputMediaStreamTrack(e){var i;return super.setOutputMediaStreamTrack(e),(i=this.room)==null?void 0:i.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 i;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){let i=e;try{if(!this.isNeedToSwitchDevice(i))return;(i===h.FACING_MODE_USER||i===h.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,i=void 0),this.mediaTrack.stop(),yield this.capture({deviceId:i,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 i=yield Ge();i[0]?this.recapture(i[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 Hh=function(r){return p(this,null,function*(){let t=null,e=Gh(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let i=yield navigator.mediaDevices.getDisplayMedia(e);if(r.systemAudio&&i.getAudioTracks().length===0&&(Gi&&mi<74||$e||Q)&&A.warn("Your browser not support capture system audio"),r.frameRate&&i.getVideoTracks()[0]&&i.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)}`),t=yield navigator.mediaDevices.getUserMedia(s),i.addTrack(t.getAudioTracks()[0])}return i})};function Fh(r){let t={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return T(r.microphoneId)||(t.deviceId=r.microphoneId),{audio:t,video:!1}}function Gh(r){let t={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(t.video=e,r.systemAudio){let{echoCancellation:i=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;t.audio={echoCancellation:i,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return t}var xd=Hh;var xe=class extends Le{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:i,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:i,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:I.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(t){super(t),this._log.id=`s-${this._log.id}`}};var nr=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 i=this.audioContext.createMediaStreamSource(new MediaStream([e]));this._inputs.set(e,i),i.connect(this._destination),this._outputTrack||(this._outputTrack=this._destination.stream.getAudioTracks()[0],this.setStateToCapture())}publish(e,i){return this.room=e,i}unpublish(){delete this.room}replaceTrack(e,i){var s;!this.hasMix||(i&&((s=this._inputs.get(i))==null||s.disconnect(),this._inputs.delete(i)),this.setInputMediaStreamTrack(e.outMediaTrack))}removeTrack(e){var i;(i=this._inputs.get(e))==null||i.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([Z("capture","publish",{ignoreError:!0})],nr.prototype,"publish",1),y([Z([],"capture")],nr.prototype,"unpublish",1);var ti=class extends Oe{constructor(e,i){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=i.url,this.audio.crossOrigin="anonymous",ie(i.loop)&&this.loop(i.loop),q(i.volume)&&this.setVolume(i.volume),i.id&&(this.musicId=i.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,i;(e=this._source)==null||e.disconnect(),(i=this._destination)==null||i.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&&ie(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",Ni="output",wd="ondump",Vd="dumped";function Wh(r){let t;return Kh(r)?t="intl-schedule.rtc.qq.com":t="schedule.rtc.qq.com",t}var Kh=r=>(r=Number(r),r>0&&r<14e8);function Ud(s){return p(this,arguments,function*({sdkAppId:r,userId:t,userSig:e,timestamp:i}){let n=`https://${Wh(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${t}&userSig=${e}&timestamp=${i}`,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.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:g="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:u?`${f} Reason: ${u}. ${g}`:`${f}, ${g}`}})}var $d=Ne(Me(),1);function Bd(r,t){t=t||{};let e=r.numberOfChannels,{sampleRate:i}=r,s=t.float32?3:1,o=s===3?32:16,n;return e===2?n=jh(r.getChannelData(0),r.getChannelData(1)):n=r.getChannelData(0),Jh(n,s,i,e,o)}function Jh(r,t,e,i,s){let o=s/8,n=i*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,t,!0),c.setUint16(22,i,!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),t===1?Xh(c,44,r):Yh(c,44,r),a}function jh(r,t){let e=r.length+t.length,i=new Float32Array(e),s=0,o=0;for(;s<e;)i[s++]=r[o],i[s++]=t[o],o++;return i}function Yh(r,t,e){for(let i=0;i<e.length;i++,t+=4)r.setFloat32(t,e[i],!0)}function Xh(r,t,e){for(let i=0;i<e.length;i++,t+=2){let s=Math.max(-1,Math.min(1,e[i]));r.setInt16(t,s<0?s*32768:s*32767,!0)}}function Ro(r,t,e){for(let i=0;i<e.length;i++)r.setUint8(t+i,e.charCodeAt(i))}var da=class{constructor(t){d(this,"audioContext_");d(this,"inputPCM_",new Float32Array);d(this,"outputPCM_",new Float32Array);this.audioContext_=t}onDump(t,e){if(e===ii){let i=this.inputPCM_.length,s=new Float32Array(i+t[0].length);s.set(this.inputPCM_),s.set(t[0],i),this.inputPCM_=s}if(e===Ni){let i=this.outputPCM_.length,s=new Float32Array(i+t[0].length);s.set(this.outputPCM_),s.set(t[0],i),this.outputPCM_=s}}getBlob(t){let e=t===ii?this.inputPCM_:this.outputPCM_,i=this.audioContext_.createBuffer(2,e.length,48e3);i.copyToChannel(e,0,0),i.copyToChannel(e,1,0);let s=Bd(i),o=new window.Blob([new DataView(s)],{type:"audio/wav"});return i=null,o}reset(){this.inputPCM_=new Float32Array,this.outputPCM_=new Float32Array}destroy(){this.reset()}},ua=da;var la=class{constructor({sdkAppId:t,userId:e,audioContext:i,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_=i,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(t),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:g}=m;this.dump_.onDump(f,ii),this.dump_.onDump(g,Ni)}l===Vd&&this.dumped()},this.dump_=new ua(this.audioContext_)}dumped(){this.isDumping_=!1;let t=this.dump_.getBlob(ii),e=this.dump_.getBlob(Ni);this.emitter_.emit("ondumpend",{blob:t,name:ii}),this.emitter_.emit("ondumpend",{blob:e,name:Ni}),this.dumpedWAV(t,ii),this.dumpedWAV(e,Ni),this.dump_.reset()}dumpedWAV(t,e){let i=window.URL.createObjectURL(t),s=document.createElement("a");s.href=i,s.download=`${e}-${Date.now()}.wav`,s.click(),window.URL.revokeObjectURL(i),s.href=""}process(t){return p(this,null,function*(){if(this.audioTrack_=t,!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 i=this.destination_.stream;return this.denoiserTrack_=i.getAudioTracks()[0],this.log_.info(`RTCAIDenoiser: denoiser process track ID: ${t.id} success.`),this.denoiserTrack_})}updateTrack(t){return p(this,null,function*(){var s;let e=new MediaStream;yield e.addTrack(t);let i=this.audioContext_.createMediaStreamSource(e);this.source_.disconnect(),i.connect(this.workletNode_),(s=this.audioTrack_)==null||s.stop(),this.audioTrack_=t,this.source_=i,this.log_.info("RTCAIDenoiser: updateTrack success.")})}disable(){return p(this,null,function*(){var t,e;return this.enableDenoise_=!1,(t=this.workletNode_)==null||t.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 t,e;return this.enableDenoise_=!0,(t=this.workletNode_)==null||t.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 ua(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 t,e,i,s,o,n;this.log_.info("RTCAIDenoiser: destroy processor."),(t=this.audioTrack_)==null||t.stop(),(e=this.workletNode_)==null||e.port.postMessage({type:"destroy"}),this.workletNode_.port.onmessage=null,(i=this.source_)==null||i.disconnect(),(s=this.destination_)==null||s.disconnect(),(o=this.workletNode_)==null||o.disconnect(),(n=this.dump_)==null||n.destroy(),this.emitter_.removeAllListeners()}on(t,e,i){this.emitter_.on(t,e,i)}off(t,e,i){t==="*"?this.emitter_.removeAllListeners():this.emitter_.off(t,e,i)}},Hd=la;var ha=class{constructor({assetsPath:t,log:e,audioContext:i}){this.isLoaded_=!1;this.audioContext_=i,this.log_=e,this.assetsPath_=t}createProcessor(t){return p(this,null,function*(){let e=String(Date.now()).slice(0,-3),{auth:i,sign:s,status:o,message:n}=yield Ud(M(N({},t),{timestamp:e}));if(!i)throw this.log_.info(`RTCAIDenoiser: ${t.userId} auth result: ${i}. 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 Hd(M(N({},t),{audioContext:this.audioContext_,timestamp:e,sign:s,status:o,worklet:a,logger:this.log_}));return this.log_.info(`RTCAIDenoiser: ${t.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(t){throw this.log_.error(`Init assets from ${this.assetsPath_} failed! Reason: ${t}`),t}})}initWorklet(){return p(this,null,function*(){try{return new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}catch(t){return yield this.load(),new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}})}destroy(){var t;(t=this.audioContext_)==null||t.close()}isSupported(){return"AudioWorklet"in window&&"WebAssembly"in window}},Fd=ha;var Co=class{constructor({room:t}){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:t.userId,sdkAppId:t.sdkAppId})}get mixedAudioTrack(){return this.localMixAudioTrack?this.localMixAudioTrack.outMediaTrack:null}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(t,e){var i,s;if(t instanceof xt){this._localScreenAudioTrack=t,t._outputTrack=t.mediaTrack;return}if(t instanceof ti){t._outputTrack=t.mediaTrack,(i=this.localMixAudioTrack)==null||i.replaceTrack(t,e);return}if(t instanceof ve){this._localAudioTrack=t,this.isDenoiserProcessed?((s=this.denoiserProcessor)==null||s.updateTrack(t.mediaTrack),t._outputTrack=this.denoiserTrack):t._outputTrack=t.mediaTrack;return}if(t instanceof wt)return t.setOutputMediaStreamTrack(t.mediaTrack)}removeInput(t){if(t instanceof ve)return this.removeAudioTrack(t);t instanceof wt}addMusicSource(t){return p(this,null,function*(){this._log.info(`add music source, id: ${t.id} url: ${t.url}`);let{id:e,url:i,loop:s,volume:o}=t;if(this.mixedMusicMap.has(e))return;let n;return this.cacheMusicMap.has(e)?n=this.cacheMusicMap.get(e):n=new ti(this,t),n.play(),this._log.info(`start mix audio ${e} success.`),this.mixedMusicMap.set(e,n),this.cacheMusicMap.set(e,n),n})}updateMusicSource(t){return p(this,null,function*(){let{id:e,volume:i,loop:s,operation:o,seekFrom:n}=t;if(this._log.info(`update music source, ${JSON.stringify(t)}`),this.mixedMusicMap.has(e)){let a=this.mixedMusicMap.get(e);T(i)||a.setVolume(i),T(s)||a.loop(s),T(o)||a.setOperation(o),T(n)||a.seek(n)}})}addAudioTrack(t){return p(this,null,function*(){var e;if(this.localMixAudioTrack||(this.localMixAudioTrack=new nr(this)),this._log.info(`start add audioTrack, userId: ${t.userId}`),t===this._localAudioTrack){if(tt){let i=yield(e=t.mediaTrack)==null?void 0:e.getSettings();this.localMixAudioTrack.channelCount=(i==null?void 0:i.channelCount)||1}this.mixedMusicMap.forEach(i=>{var s;(s=this.localMixAudioTrack)==null||s.setInputMediaStreamTrack(i.outMediaTrack)})}this.localMixAudioTrack.setInputMediaStreamTrack(t.outMediaTrack)})}removeAudioTrack(t){!this.localMixAudioTrack||(t===this._localAudioTrack&&this.mixedMusicMap.forEach(e=>{this.localMixAudioTrack.removeTrack(e.outMediaTrack)}),this.localMixAudioTrack.removeTrack(t.outMediaTrack))}removeMusicSource({id:t}){if(!!this.localMixAudioTrack){if(this.mixedMusicMap.has(t)){this._log.info(`remove music source, music id: ${t}`);let e=this.mixedMusicMap.get(t);e.stop(),this.localMixAudioTrack.removeTrack(e.outMediaTrack),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()}}destroyAllMusic(){this._log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{this.removeMusicSource({id:e})})}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach(t=>t.stop())}initDenoiser(t){return p(this,null,function*(){let{assetsPath:e,sdkAppId:i,userId:s,userSig:o}=t;try{(!this.denoiserContext||this.denoiserContext.state==="closed")&&(this.denoiserContext=_t("denoiser")),this.denoiser||(this.denoiser=new Fd({assetsPath:e,log:this._log,audioContext:this.denoiserContext})),this.denoiserProcessor||(this.denoiserProcessor=yield this.denoiser.createProcessor({sdkAppId:i,userId:s,userSig:o})),this.isDenoiserInit=!0,this.initProcessorOptions=t}catch(n){throw n}})}enableDenoiser(t){return p(this,null,function*(){var e,i,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,(i=this.localMixAudioTrack)==null||i.replaceTrack(this._localAudioTrack,o)}})}disableDenoiser(){return p(this,null,function*(){var t;this.isDenoiserEnabled&&((t=this.denoiserProcessor)==null||t.disable(),this.isDenoiserEnabled=!1)})}destroyDenoiserProcessor(){var t;this.denoiserProcessor&&(this.denoiserProcessor.destroy(),delete this.denoiserProcessor,this.isDenoiserInit=!1,this.isDenoiserEnabled=!1,this.isDenoiserProcessed=!1,(t=this.denoiserTrack)==null||t.stop(),this.denoiserTrack=null),this.denoiserContext&&(this.denoiserContext.close(),delete this.denoiserContext)}destroy(){var t;this.destroyAllMusic(),this.destroyAllCache(),this.destroyDenoiserProcessor(),(t=this.denoiser)==null||t.destroy(),this.localMixAudioTrack&&(this.localMixAudioTrack.close(),delete this.localMixAudioTrack)}};var ma=class extends Ci{constructor(e,i,s){super({userId:i.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=i;d(this,"tinyId");d(this,"isRemote",!0);this.tinyId=i.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===ma.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=ma;d(rt,"STATE_SUBSCRIBE","subscribe"),y([Z(P.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([Z(rt.STATE_SUBSCRIBE,P.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,i){super(e,i,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 i=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==i}};var ft=class extends rt{constructor(e,i,s=4){super(e,i,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 i=e.hasVideo&&!e.videoMuted;return this.hasFlag!==i}},ar=class extends ft{constructor(e,i){super(e,i,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let i=e.hasAuxiliary;return this.hasFlag!==i}};function he(...r){}var Qh=r=>r();function _a(){this.dispose()}var qh=()=>typeof __FASTRX_DEVTOOLS__!="undefined",zh=1,Vt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new pa(t,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(t){}complete(){this.dispose()}error(t){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(t){return t instanceof Vt?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Qh),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},w=class extends ls{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}};function Gd(r,...t){return t.reduce((e,i)=>i(e),r)}function Ut(r,t,e){if(qh()){let i=Object.defineProperties(Object.setPrototypeOf(r,Vt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});st.create(i);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof Vt&&st.addSource(i,o)}return i}return r}function H(r,t){return function(...e){return i=>{if(i instanceof Vt){let s=Ut(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(i)},t,arguments);return s.source=i,st.pipe(s),s}else return s=>i(new r(s,...e))}}}function ri(r,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:t}})}var pa=class extends w{constructor(t,e,i){super(t),this.source=e,this.id=i,this.sourceId=t.sourceId,this.defer(()=>{st.defer(this.source,this.id)})}next(t){st.next(this.source,this.id,t),this.sink.next(t)}complete(){st.complete(this.source,this.id),this.sink.complete()}error(t){st.complete(this.source,this.id,t),this.sink.error(t)}},st={addSource(r,t){ri("addSource",{id:r.id,name:r.toString(),source:{id:t.id,name:t.toString()}})},next(r,t,e){ri("next",{id:r.id,streamId:t,data:e&&e.toString()})},subscribe({id:r,end:t},e){ri("subscribe",{id:r,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,t,e){ri("complete",{id:r.id,streamId:t,err:e?e.toString():null})},defer(r,t){ri("defer",{id:r.id,streamId:t})},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=zh++),ri("create",{name:r.toString(),id:r.id})}},No=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var fa=class extends ls{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function yo(){return r=>{let t=new fa(r);if(r instanceof Vt){let e=Ut(i=>{t.add(i)},"share",arguments);return t.sourceId=e.id,e.source=r,st.pipe(e),e}return Ut(t.add.bind(t),"share",arguments)}}function Zh(...r){return Ut(t=>{let e=r.length,i=e,s=e,o=new Array(e),n=()=>{--s===0&&t.complete()},a=(c,u)=>{let l=new w(t);l.next=m=>{--i===0?(l.next=f=>{o[u]=f,t.next(o)},l.next(m)):o[u]=m},l.complete=n,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Ea=class extends w{constructor(t,...e){super(t);let i=new w(this.sink);i.next=s=>this.buffer=s,i.complete=he,i.subscribe(Zh(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},iI=H(Ea,"withLatestFrom"),Ta=class extends w{constructor(t,e,i){super(t),this.bufferSize=e,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},rI=H(Ta,"bufferCount"),Ia=class extends w{constructor(t,e){super(t),this.buffer=[];let i=new w(t);i.next=s=>{t.next(this.buffer),this.buffer=[]},i.complete=he,i.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},sI=H(Ia,"buffer");function Sa(r){let t=arguments,e=yo()(Ut(i=>{e.next=s=>i.next(s),e.complete=()=>i.complete(),e.error=s=>i.error(s),r&&i.subscribe(r)},"subject",t));return e.next=he,e.complete=he,e.error=he,e}function Wd(r){return Ut(t=>{let e=0,i=setInterval(()=>t.next(e++),r);return t.defer(()=>{clearInterval(i)}),"interval"},"interval",arguments)}var ga=class extends w{constructor(t,e,i){super(t),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof i=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=i,this.complete=s)}next(t){this.acc=this.f(this.acc,t)}},em=H(ga,"reduce");var Aa=class extends w{constructor(t,e,i){super(t),this.filter=e,this.thisArg=i}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},tm=H(Aa,"filter"),Ra=class extends w{next(t){}},_I=H(Ra,"ignoreElements"),Ca=class extends w{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},im=H(Ca,"take"),Na=class extends w{constructor(t,e){super(t);let i=new w(t);i.next=()=>t.complete(),i.complete=_a,i.subscribe(e)}},fI=H(Na,"takeUntil"),ya=class extends w{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},rm=H(ya,"takeWhile");var ba=class extends w{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},EI=H(ba,"skip"),Oa=class extends w{constructor(t,e){super(t),t.next=he;let i=new w(t);i.next=()=>{i.dispose(),t.resetNext()},i.complete=_a,i.subscribe(e)}},TI=H(Oa,"skipUntil"),Da=class extends w{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},sm=H(Da,"skipWhile"),om={leading:!0,trailing:!1},va=class extends w{constructor(t,e,i){super(t),this.durationSelector=e,this.trailing=i}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},La=class extends w{constructor(t,e,i=om){super(t),this.durationSelector=e,this.config=i,this._throttle=new va(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=he,this._throttle.complete(),super.complete()}},II=H(La,"throttle");var Ma=class extends w{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Pa=class extends w{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Ma(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},SI=H(Pa,"debounce");var ka=class extends w{constructor(t,e,i){super(t),this.count=e,this.defaultValue=i}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},gI=H(ka,"elementAt");var xa=class extends w{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},AI=H(xa,"findIndex"),wa=class extends w{constructor(t,e,i){super(t),this.f=e,this.defaultValue=i,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},RI=H(wa,"first"),Va=class extends w{constructor(t,e,i){super(t),this.f=e,this.defaultValue=i,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},CI=H(Va,"last"),Ua=class extends w{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},NI=H(Ua,"every");var Ba=class extends w{constructor(t,e,i){super(t),this.f=e,typeof i=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=i}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},DI=H(Ba,"scan"),$a=class extends w{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},vI=H($a,"pairwise"),Ha=class extends w{constructor(t,e,i){super(t),this.mapper=e,this.thisArg=i}next(t){super.next(this.mapper.call(this.thisArg,t))}},Kd=H(Ha,"map");var cr=class extends w{constructor(t,e,i){super(t),this.data=e,this.context=i}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},dr=class extends w{constructor(t,e,i){super(t),this.makeSource=e,this.combineResults=i,this.index=0}subInner(t,e){let i=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},bo=class extends cr{},Oo=class extends dr{next(t){this.subInner(t,bo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,bo)}}},nm=H(Oo,"switchMap");function Mo(r){return(t,e)=>r(()=>t,e)}var LI=Mo(H(Oo,"switchMapTo")),Fa=class extends cr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Do=class extends dr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),Fa),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},MI=H(Do,"concatMap"),PI=Mo(H(Do,"concatMapTo")),Ga=class extends cr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},vo=class extends dr{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Ga),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},kI=H(vo,"mergeMap"),xI=Mo(H(vo,"mergeMapTo")),Wa=class extends cr{dispose(){this.context.resetNext(),super.dispose()}},Lo=class extends dr{next(t){this.next=he,this.subInner(t,Wa)}},wI=H(Lo,"exhaustMap"),VI=Mo(H(Lo,"exhaustMapTo")),Ka=class extends w{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),i=this.groups.get(e);typeof i=="undefined"&&(i=Sa(),i.key=e,this.groups.set(e,i),super.next(i)),i.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},UI=H(Ka,"groupBy"),Ja=class extends w{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},BI=H(Ja,"timeInterval"),ja=class extends w{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},$I=H(ja,"bufferTime"),Ya=class extends w{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:i,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(i))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},HI=H(Ya,"delay"),Xa=class extends w{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},FI=H(Xa,"catchError");var Qa=class extends w{constructor(t,e){super(t),e instanceof Function?this.next=i=>{e(i),t.next(i)}:(e.next&&(this.next=i=>{e.next(i),t.next(i)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=i=>{e.error(i),t.error(i)}))}},JI=H(Qa,"tap"),qa=class extends w{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new No(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},jI=H(qa,"timeout");var uS=Gd(Wd(250),Kd(()=>performance.now()),yo());var ur=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 t=32769;r.mediaType===4?t=32768:r.mediaType===2&&(t=32805),pe(r.room.userId,{eventId:t,eventDesc:`publish ${r.kind}`})}});E.on(_.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let t=32771;r.mediaType===4?t=32770:r.mediaType===2&&(t=32806),pe(r.room.userId,{eventId:t,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:t,state:e})=>{let i,s;switch(e){case"CONNECTED":t==="RECONNECTING"?(i=32795,s="signal reconnected"):(i=32791,s="signal connected");break;case"DISCONNECTED":t==="RECONNECTING"?(i=32796,s="signal reconnect fail"):(i=32790,s="signal disconnected");break;case"RECONNECTING":i=32794,s="signal reconnecting";break}i&&s&&pe(r.userId,{eventId:i,eventDesc:s})});E.on(_.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:t,state:e,remoteUserId:i})=>{let s=!!i,o=s?"downlink":"uplink",n,a;switch(e){case"CONNECTED":t==="RECONNECTING"?(n=s?32801:32798,a=`${o} reconnected`):(n=s?32793:32792,a=`${o} connected`);break;case"DISCONNECTED":t==="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:i})});function pe(r,t){let e=M(N({},t),{timestamp:Rr()});ur.has(r)?ur.get(r).push(e):ur.set(r,[e])}function Jd(r){if(ur.has(r)){let t=ur.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return ur.delete(r),t}return[]}var jd=Ne(Me(),1);var Po=class extends jd.EventEmitter{constructor(e,i,s="userId"){super();this.mySelfId=e;this._log=i;this.key=s;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let i=e[this.key],{userId:s,tinyId:o,role:n}=e;if(this.userMap.has(i))return;let a={userId:s,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(i,a),this.emit("1",a)}deleteUser(e,i){let s=this.userMap.get(e);if(!s)return;let o=`peer leave [${e}]`;T(i)||(o+=`:${wn[i]}`),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(i=>{e.findIndex(s=>s[this.key]===i[this.key])<0&&this.deleteUser(i[this.key],0)}),e.forEach(i=>{!this.userMap.has(i[this.key])&&i[this.key]!==this.mySelfId&&this.addUser(i)})}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(i=>{let s=i[this.key];if(e.findIndex(o=>o[this.key]===i[this.key])<0){this._log.info(`remote [${s}] unpublish`);let o=i.muteState;i.flag=0,this.emit("5",i.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:o,muteState:i.muteState,flag:0})}}),e.forEach(i=>{var l;let s=i[this.key];if(s===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=i,c=Xt(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",i),this.emit("6",{prevMuteState:Xt(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Yd({timesInSecond:r,maxSizeInSecond:t,getSize:e}){return G((i,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>t))throw new C({code:I.INVALID_OPERATION,message:D({key:O.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>t,name:s,timesInSecond:r,maxSizeInSecond:t}})});a.callCountInSecond++,i.call(this,...n)}})}var Xd=!0,Qd=function(){var r;Xd&&(Xd=!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:",Se),A.info("UA:",navigator.userAgent),A.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),Ur().then(t=>{if(t){let e=`UAData: ${t.platform}/${t.platformVersion}`;t.architecture&&t.bitness&&(e+=` ${t.architecture}/${t.bitness}`),t.mobile&&(e+=" mobile"),t.model&&(e+=` model: ${t.model}`),t.fullVersionList&&(e+=` ${t.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.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:t,enableDocLink:e=!1}){let i="",s,o=si[r];try{s=qd[o]}catch(n){s=qd.UNKNOWN_ERROR}return j(s)?i=s(t):Y(s)&&(i=s),e&&(i+=" doc:"),i}var qd=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:t,fnName:e,value:i}){return`'${r||t.name}' is a required param when calling ${e}(), received: ${i}.`},INVALID_PARAMETER_TYPE({key:r,rule:t,fnName:e,value:i}){let s=`${r||t.name}`,o="";return Array.isArray(t.type)?o=t.type.join("|"):o=t.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${oe(i)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:t,fnName:e,value:i}){return`'${r||t.name}' cannot be '${i}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:t,fnName:e,value:i}){let s=`${r||t.name}`,o=`${t.instanceOf.name||t.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${oe(i)}.`},INVALID_PARAMETER_RANGE({key:r,rule:t,fnName:e,value:i}){return`'${r||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${i}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:t,fnName:e}){return`'${r||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:t,value:e}){return`the min value of ${r||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:t,value:e}){return`the max value of ${r||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:t}){return`'${r}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:t,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${t}(), 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:t}){return`cannot ${r} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:t}){return`cannot ${r} because remote user(userId: ${t.userId}) does not publishing ${t.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:t}){return`'${r}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:t=yi(r),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:t=yi(r),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:t=yi(r),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:t=yi(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:t=yi(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:t=yi(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:t=yi(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:t}){return`'${r}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:t}){return`video context error ${r} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:r,error:t}){return`'${r}' got server error: ${t==null?void 0:t.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:t}){return`'${r}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function yi(r){if(!r)return"camera";let t=r.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var lr=class extends Error{constructor({code:e,extraCode:i,message:s="",messageParams:o,fnName:n="",originError:a}){var u;let c;s?c=s:c=zd({code:i||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=i,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,i,s){let o=e;if(e instanceof C){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:i,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER;break;case I.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(me.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:a.code=U.DEVICE_ERROR;break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=U.OPERATION_ABORT;break;case I.INITIALIZE_FAILED:a.code=5300,a.extraCode=am(e.name);break;case I.UNKNOWN:break;default:a.code=U.OPERATION_FAILED}o=new lr(a),n&&(o.stack+=n.substr(n.indexOf(`
29
- `)))}else o=new lr({code:U.UNKNOWN_ERROR,fnName:i,originError:e});return o}};function am(r){let t;switch(r){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var k=lr;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}}},hr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,t,e){if(Y(r)){let i=document.getElementById(r);if(!i)throw new k({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}});if(!(i instanceof HTMLElement))throw new k({code:U.INVALID_PARAMETER,extraCode:5010,fnName:e,messageParams:{key:t,type:oe(i)}})}}},tu={name:"userId",required:!0,type:"string"},iu={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0,max:100},earMonitorVolume:{type:"number",min:0,max:100},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function xo(r,t){if(!r)throw new k({code:U.INVALID_OPERATION,extraCode:5101,fnName:t})}function ru(r,t,e){if(!r)throw new k({code:U.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var eA={type:"number",notLessThanZero:!0},cm={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,t,e){if(this._room.isJoined)throw new k({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new k({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:U.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new k({code:U.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new k({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:hr,publish:{type:"boolean"},option:Zd},validate(r){var t;if(!((t=r==null?void 0:r.option)!=null&&t.videoTrack)&&qt())throw new k({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:M(N({},hr),{required:!1}),publish:{type:"boolean"},mute:{type:"boolean"},option:Zd}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:iu},validate(r){var t;if(!((t=r==null?void 0:r.option)!=null&&t.audioTrack)&&qt())throw new k({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:hr,publish:{type:"boolean"},option:eu},validate(r,t,e,i,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&qt())throw new k({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!Zr())throw new k({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:hr,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:hr,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,t,e){xo(this._room.isJoined,e);let i=this._room.remotePublishedUserMap.get(r.userId);if(ru(!!i,e,r),i&&(r.streamType==="main"&&!i.muteState.videoAvailable||r.streamType==="sub"&&!i.muteState.hasAuxiliary))throw new k({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:M(N({},hr),{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,t,e){xo(this._room.isJoined,e);let i=this._room.remotePublishedUserMap.get(r.userId);if(ru(!!i,e,r),i&&(r.streamType==="main"&&!i.muteState.videoAvailable||r.streamType==="sub"&&!i.muteState.hasAuxiliary))throw new k({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,t,e){if(r.userId!=="*"&&T(r.streamType))throw new k({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,t,e){xo(this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,t,e,i){if(!Zt)throw new k({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:U.INVALID_OPERATION,messageParams:{key:O.SEI_DISABLED}});if(r.byteLength>1e3)throw new k({code:U.INVALID_PARAMETER,messageParams:{key:O.SEI_OVERSIZE,data:r.byteLength}});if(r.byteLength===0)throw new k({code:U.INVALID_PARAMETER,messageParams:{key:O.SEI_EMPTY}});if(xo(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new k({code:U.INVALID_PARAMETER,messageParams:{key:O.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},_e={TRTC:cm};var Te=class extends Error{};function dm(r,t){let e=[];return lt(e,r),lt(e,t),e}function um(r){this._resolve=Promise.resolve(r)}function lm(r){this._reject=Promise.reject(r)}var mr=class{constructor(t,e){this.instance=t;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",dm);let i=mr.instances.get(t);i?i.set(e,this):mr.instances.set(t,new Map([[e,this]]))}static get(t,e){let i=mr.instances.get(t);return i&&i.get(e)||new mr(t,e)}action(t,e,i){let s=a=>{var c;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,u;throw this.ops.shift(),t===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Te("start failed")),(u=this.currentOp)==null||u.action(),a},n={type:t,action:()=>e(...n.args).then(s,o),args:i,resolve:um,reject:lm};try{switch(this.state){case 1:if(t===0)throw new Te("already started");break;case 4:if(t===2)throw new Te("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(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Te("already start");break;case 3:switch(t.type){case 2:throw new Te("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Te("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let i=new Te("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(i)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Te("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Te("start not allowed after update");case 0:throw new Te("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Te("keep start")),new Te("already start")}}t.promise=new Promise((i,s)=>{t._resolve?t._resolve.then(i):t.resolve=i,t._reject?t._reject.catch(s):t.reject=s});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Bt=mr;d(Bt,"instances",new WeakMap);var za=(r,t)=>{if(t instanceof Te){let{stack:e}=t;t=new k({code:U.OPERATION_ABORT,message:`${r} abort: ${t.message}`,fnName:r}),e&&(t.stack+=e.substr(e.indexOf(`
30
- `)))}throw t};function oi(r,t){return G((e,i)=>function(...s){let o=Bt.get(this,typeof r=="string"?r:r.call(this,...s));return t&&(o.startSame=t.bind(this)),o.action(0,e.bind(this),s).catch(za.bind(null,i))})}function bi(r,t){return G((e,i)=>function(...s){let o=Bt.get(this,typeof r=="string"?r:r.call(this,...s));return t&&(o.mergeUpdate=t.bind(this)),o.action(2,e.bind(this),s).catch(za.bind(null,i))})}function ni(r){return G((t,e)=>function(...i){return Bt.get(this,typeof r=="string"?r:r.call(this,...i)).action(3,t.bind(this),i).catch(za.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 wo(r){return{room:r,innerEmitter:E,constants:Vn,environment:Kt,utils:ge,eventLogger:X,log:r.getLogger(),clearStarted(t,e){let i=t.getAlias(),s=Bt.instances.get(r);if(!!s)if(e){let o=s.get(i+e);if(!o)return;o.started=!1}else s.forEach((o,n)=>{n.startsWith(i)&&(o.started=!1)})}}}var au=(r,t)=>{let{emit:e}=r;return r.emit=(...i)=>{try{return e.apply(r,i)}catch(s){let o=D({key:O.CATCH_HANDLER_ERROR,data:{name:t,event:i[0]},addDocLink:!1});return A.warn(`${o}
28
+ `,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(`.${nr}`).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={};Rr(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(er,()=>{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}-${Oe.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:Oe.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,Ni=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(Ni.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(Ni.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 yi=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 De?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof De}),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 Ni({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)],yi.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=ye(Le(),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(Si,()=>{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 ar(){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===gi);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===gi?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:Oe.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{q.logSuccessEvent({eventType:Oe.GET_USER_MEDIA_RETRY}),q.uploadEvent({log:`stat-${Oe.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 De=class extends yi{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})],De.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})}})],De.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")],De.prototype,"unpublish",1);var us=new Map;E.on(_.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&us.delete(r.track.deviceId)});var ke=class extends De{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===gi){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 Me=class extends De{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.width*e.height<=160*120&&Ie&&mi&&(this.log.warn(`resolution is ${e.width}*${e.height}, fallback to 240*180`),e.width>e.height?(e.width=240,e.height=180):(e.width=180,e.height=240),e.bitrate=Math.max(e.bitrate,150)),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&&(Ki&&pi<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 Me{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 ke{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var cr=class extends ke{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})],cr.prototype,"publish",1),y([ee([],"capture")],cr.prototype,"unpublish",1);var ti=class extends De{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",bi="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=ye(Le(),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===bi){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,bi)}l===Vd&&this.dumped()},this.dump_=new ha(this.audioContext_)}dumped(){this.isDumping_=!1;let i=this.dump_.getBlob(ii),e=this.dump_.getBlob(bi);this.emitter_.emit("ondumpend",{blob:i,name:ii}),this.emitter_.emit("ondumpend",{blob:e,name:bi}),this.dumpedWAV(i,ii),this.dumpedWAV(e,bi),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 ke){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 ke)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 cr(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 yi{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}},dr=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])}},ig=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()}},rg=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()}},sg=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){}},_g=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)}},fg=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)}},Eg=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)}},Tg=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()}},gg=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()}},Sg=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()}},Ig=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}},Ag=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()}},Rg=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()}},Cg=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()}},Ng=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))}},Dg=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}},vg=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 ur=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()}},lr=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 ur{},Oo=class extends lr{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 kg=Mo(F(Oo,"switchMapTo")),Wa=class extends ur{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Do=class extends lr{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()}},Mg=F(Do,"concatMap"),Lg=Mo(F(Do,"concatMapTo")),Ka=class extends ur{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},vo=class extends lr{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()}},Pg=F(vo,"mergeMap"),xg=Mo(F(vo,"mergeMapTo")),Ja=class extends ur{dispose(){this.context.resetNext(),super.dispose()}},ko=class extends lr{next(i){this.next=he,this.subInner(i,Ja)}},wg=F(ko,"exhaustMap"),Vg=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)}},Ug=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}},Bg=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()}},$g=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)}},Fg=F(qa,"delay"),Xa=class extends w{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Hg=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)}))}},Jg=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 uS=Gd(Wd(250),Kd(()=>performance.now()),yo());var hr=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:Nr()});hr.has(r)?hr.get(r).push(e):hr.set(r,[e])}function Jd(r){if(hr.has(r)){let i=hr.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return hr.delete(r),i}return[]}var jd=ye(Le(),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:",Ae),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=Oi(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=Oi(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=Oi(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=Oi(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=Oi(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=Oi(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=Oi(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 Oi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var mr=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 mr(a),n&&(o.stack+=n.substr(n.indexOf(`
29
+ `)))}else o=new mr({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=mr;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}}},pr={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 eA={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:pr,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({},pr),{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:pr,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:pr,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:pr,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({},pr),{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 _r=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=cm;let t=_r.instances.get(i);t?t.set(e,this):_r.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=_r.instances.get(i);return t&&t.get(e)||new _r(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=_r;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(`
30
+ `)))}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 Di(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:Re,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}
31
31
 
32
- ${s.stack}`),!1}},r};var Vo=new WeakMap;function cu(r,t){return G((e,i)=>function(...s){var a,c;let o=(a=Vo.get(this))==null?void 0:a.get(t(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Vo.has(this)?(c=Vo.get(this))==null||c.set(t(...s),n):Vo.set(this,new Map([[t(...s),n]]))})}var du="5.2.0";function Ae(...r){return G((t,e)=>function(...i){try{Bo.call(this,r,i,e,this._name)}catch(s){return Promise.reject(s)}return t.apply(this,i)})}function Za(...r){return G((t,e)=>function(...i){try{Bo.call(this,r,i,e,this._name)}catch(s){throw s}return t.apply(this,i)})}function Bo(r,t,e,i){if(de(r))for(let s=0;s<r.length;s++)Uo.call(this,{rule:r[s],value:t[s],key:r[s].name,fnName:e,className:i});else Uo.call(this,{rule:r,value:t[0],key:r.name,fnName:e,className:i})}function Uo({rule:r,value:t,key:e,fnName:i,className:s}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:i,messageParams:{key:e,rule:r,value:t}}}if(T(t)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){j(r.validate)&&r.validate.call(this,t,e,i,s,this);return}t=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let u=0;u<r.type.length;u++)r.type[u]===null&&t===null&&(c=!0),j(r.type[u])&&t instanceof r.type[u]&&(c=!0),Y(r.type[u])&&oe(t)===r.type[u].toLowerCase()&&(c=!0);if(!c)throw new k({code:U.INVALID_PARAMETER,extraCode:5002,fnName:i,messageParams:{key:e,rule:{type:r.type.map(u=>Qr(u)?uo(u):Y(u)?u:oe(u))},value:t}})}else if(!T(r.type)&&oe(t)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=q(t)&&(t===0||Number.isNaN(t)),u=Y(t)&&t.trim()==="";if(c||u)throw new k(o(5003))}if(r.notLessThanZero&&q(t)&&t<0)throw new k(o(5006));if(!T(r.min)&&q(t)&&t<r.min)throw new k(o(5007));if(!T(r.max)&&q(t)&&t>r.max)throw new k(o(5008));if(Y(r.instanceOf)){if(!t||t._name!==r.instanceOf)throw new k(o(5004))}else if(j(r.instanceOf)&&!(t instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(t))throw new k(o(5005));let{properties:n}=r;He(n)&&Si(t)&&Object.keys(n).forEach(c=>{Uo.call(this,{rule:n[c],value:t&&t[c],key:`${c}`,fnName:i,className:s})});let{arrayItem:a}=r;He(a)&&de(t)&&t.forEach((c,u)=>{Uo.call(this,{rule:a,value:c,key:`${e}[${u}]`,fnName:i,className:s})}),j(r.validate)&&r.validate.call(this,t,e,i,s,this)}function re(r={}){let{namePrefix:t=()=>"",getRemoteId:e=()=>""}=r;return G((i,s)=>function(...o){function n(m,f,g){if(g&&g.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=t.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=i.apply(this,o),f=$();return Xr(m)?m.then(g=>(a.info(`${l}() success ${e.call(this,...o)}`),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,cost:$()-f}),g)).catch(g=>{throw g=k.convertFrom.call(this,g,l,o.length===1?o[0]:o),a.error(`${l}() failed ${e.call(this,...o)} ${g} params: ${JSON.stringify(o,n)}`),E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,error:g}),g}):(E.emit(_.API_SUCCESS_RATE,{room:this._room,apiName:l,cost:$()-f}),m)}catch(m){throw m=k.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 $o=r=>G((t,e)=>function(i,s){return p(this,null,function*(){let o=this._plugins.get(i);if(!o){this._log.warn(`plugin ${i} is not found`);return}return Bo.call(this,o.getValidateRule(r),[s],e,"TRTC"),t.call(this,o,s)})});var Ho=0,ps=class{constructor(t){this.core=t;d(this,"log");Ho=Ho+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ho}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ho}`),this.core=t}getName(){return"AudioMixer"}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return ps.startValidateRule;case"update":return ps.updateValidateRule;case"stop":return ps.stopValidateRule}}start(t){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.addMusicSource(t)})}update(t){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.updateMusicSource(t)})}stop(t){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.removeMusicSource(t)})}},Oi=ps;d(Oi,"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(t,e,i){if(t.url!=="*"){let s=["mp3","ogg","wav","flac"],o=t.url.split(".").pop(),n=s.indexOf(o)>=0,a=t.url.startsWith("blob"),c=t.url.startsWith("data");if(!(n||a||c))throw new k({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}}}),d(Oi,"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(Oi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}});var Fo=0,_s=class{constructor(t){this.core=t;d(this,"log");Fo=Fo+1,this.log=t.log.createChild({id:`${this.getAlias()}${Fo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Fo}`)}getName(){return"AIDenoiser"}getAlias(){return"ad"}getGroup(t){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return _s.startValidateRule;case"update":return _s.updateValidateRule;case"stop":return _s.stopValidateRule}}start(t){return p(this,null,function*(){let{room:e}=this.core,{assetsPath:i,sdkAppId:s,userId:o,userSig:n}=t;if(i&&!e.audioManager.isDenoiserInit)try{yield e.audioManager.initDenoiser({assetsPath:i,sdkAppId:s,userId:o,userSig:n})}catch(a){if(a.message)throw new C({code:I.INVALID_PARAMETER,message:a.message})}yield e.audioManager.enableDenoiser(t),e.sendAbilityStatus({ai_denoise:1})})}update(t){return p(this,null,function*(){})}stop(t){return p(this,null,function*(){let{room:e}=this.core;yield e.audioManager.disableDenoiser()})}},Di=_s;d(Di,"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(Di,"updateValidateRule",{type:"object"}),d(Di,"stopValidateRule",{type:"object"});var mm=0,ec=new Set,we=null;An(du);var fs=class extends lu.EventEmitter{constructor(e,i){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${++mm}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);this._room=new e(N({logger:this._log,frameWorkType:fs.frameWorkType},i)),i.plugins&&i.plugins.forEach(n=>{let a=new n(wo(this._room));this._plugins.set(a.getName(),a)});let s=new Oi(wo(this._room));this._plugins.set(s.getName(),s);let o=new Di(wo(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 k({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(()=>{})}),Ee(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===Kr){let a=(yield or()).find(c=>c.deviceId===Kr);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 or())[0];a&&we&&(we.deviceId===n.deviceId||we.deviceId===Kr&&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,i){Qd();let s=new fs(e,i||{});return ec.add(s),we?s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:we}):or().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:i="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,ie(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),Ee(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,k.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=>{Ee(f,f).add("player-state-changed",g=>{let b=M(N({},g),{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",g=>{g.getCode()===I.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,g=this._room.remotePublishedUserMap.get(f),b=l.audioAvailable,L=l.videoAvailable,{audioAvailable:se,videoAvailable:Re}=m;se||this._remoteAudioConfigMap.delete(f),Re||this._remoteVideoConfigMap.delete(`${f}_${"main"}`),m.hasAuxiliary||this._remoteVideoConfigMap.delete(`${f}_${"sub"}`),b!==se&&this.emit(se?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:f}),L!==Re&&this.emit(Re?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 k({code:U.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",l=>{this.emit(x.SEI_MESSAGE,l)}).add("heartbeat-report",l=>{var g,b,L,se,Re,ui,li;let m={2:"big",3:"small",7:"sub"},f={rtt:l.msg_up_stream_info.msg_network_status.uint32_rtt||((g=l.msg_down_stream_info[0])==null?void 0:g.msg_network_status.uint32_rtt)||((b=this._networkQuality)==null?void 0:b.uplinkRTT)||((L=this._networkQuality)==null?void 0:L.downlinkRTT)||0,upLoss:((se=this._networkQuality)==null?void 0:se.uplinkLoss)||0,downLoss:((Re=this._networkQuality)==null?void 0:Re.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)/qe},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)/qe},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,i,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(),ec.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:i=!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,T(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 k({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=k.convertFrom(c.error)),this.emit(x.PUBLISH_STATE_CHANGED,M(N({},c),{error:u}))}),yield o.capture(n),Ee(o,o).add("player-state-changed",c=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,M(N({},c),{userId:""}))}),i&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),yield this._updateAudioPlayOption({playOption:a,track:o}),this._localAudioTrack=o,this._localAudioConfig=M(N({},e),{publish:i})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:i,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),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume)),this._room.isJoined&&!T(i)&&(i&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!i&&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:i,publish:s=!0,option:o}=e,n=new Le(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 k({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=k.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}Ee(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:i,playOption:c,track:n}),this._localVideoTrack=n,this._localVideoConfig=M(N({},e),{view:i,publish:s})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:i,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:i,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:i=null,publish:s=!0,option:o}=e,n=new xe(this._room.videoManager);n.on("4",m=>{let f;m.error&&(f=k.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])),Ee(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:i,playOption:u,track:n}),this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=M(N({},e),{view:i,publish:s})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:i,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:i,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:i,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:i,playOption:u,track:l}),this._remoteVideoConfigMap.set(a,e)})}updateRemoteVideo(e){return p(this,null,function*(){let{view:i,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:i,playOption:c,track:u,prevConfig:m})),lt(m,e)})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,i=!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)i&&(yield this._room.unsubscribe(n));this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,i){return p(this,null,function*(){if(e==="*")if(i)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 i?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,i)})}setRemoteAudioVolume(e,i){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:i},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:i},track:s.remoteAudioTrack})}}startPlugin(e,i){return p(this,null,function*(){return e.start(i)})}updatePlugin(e,i){return p(this,null,function*(){return e.update(i)})}stopPlugin(e,i){return p(this,null,function*(){return e.stop(i)})}enableAudioVolumeEvaluation(e=2e3,i=!1){this._room.enableAudioVolumeEvaluation(e,i)}on(e,i,s){return super.on(e,i,s),this._eventListened.add(e),this}off(e,i,s){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,i,s),this}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:i="",streamType:s="main"}=e;if(i===""){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(i);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let i=this._room.remotePublishedUserMap.get(e);if(i)return i.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var i;(i=this._localAudioTrack)==null||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return p(this,null,function*(){let{userId:i,option:s}=e;if(this._remoteAudioConfigMap.has(i)){this._log.warn(`remote audio has already started. userId:${i}`);return}let o=this._room.remotePublishedUserMap.get(i);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(i,e)})}_stopRemoteAudio(e,i=!0){return p(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&i&&(yield this._room.unsubscribe(s.remoteAudioTrack))),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:i,track:s,prevConfig:o}){if(T(e)&&o&&o.view&&!qr(i)){let a;de(o.view)?a=o.view:a=lo(o.view),a&&(yield s.play(a,i))}if(!T(e)){let a;de(e)?a=e:a=lo(e),a?yield s.play(a,i):s.stop()}})}_updateAudioPlayOption(o){return p(this,arguments,function*({playOption:e={},track:i,prevConfig:s}){if(!i.isPlayCalled)try{yield i.play(null,e)}catch(n){}T(e.muted)||i.setPlayerMute(e.muted),T(e.volume)||i.setAudioVolume(e.volume/100)})}_checkTrackToPublish(){var i,s,o;let e=[];if(((i=this._localAudioConfig)==null?void 0:i.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&&Ee(this,this).add(x.REMOTE_AUDIO_AVAILABLE,i=>p(this,[i],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&&Ee(this,this).add(x.REMOTE_VIDEO_AVAILABLE,({userId:e,streamType:i})=>{let s=this._room.remotePublishedUserMap.get(e);s&&(i==="main"?this._room.subscribe(s.remoteVideoTrack).catch(()=>{}):i==="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 i=e.includes("main")?"main":"sub",s=e.split(`_${i}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:i}).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,i,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(),(i=this._localScreenAudioTrack)==null||i.stop(),(s=this._localScreenAudioTrack)==null||s.close(),ne(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}})}sendSEIMessage(e,i){this._room.sendSEI(e,i||{seiPayloadType:243})}static setLogLevel(e,i){A.setLogLevel(e),T(i)||(i?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Kn()}static getCameraList(){return Ge()}static getMicrophoneList(){return ke()}static getSpeakerList(){return or()}static setCurrentSpeaker(e){return p(this,null,function*(){(yield or()).forEach(s=>{s.deviceId===e&&(ec.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([Ae(_e.TRTC.enterRoom),oi("room",([r],[t])=>(r.roomId||r.strRoomId)===(t.roomId||t.strRoomId)&&r.userId===t.userId&&r.sdkAppId===t.sdkAppId),G(r=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),r.call(this,t).catch(e=>{throw ne(this),e})}),re()],J.prototype,"enterRoom",1),y([re()],J.prototype,"exitRoom",1),y([Ae(_e.TRTC.switchRole),bi("room",(r,t)=>t),re()],J.prototype,"switchRole",1),y([re()],J.prototype,"destroy",1),y([Ae(_e.TRTC.startLocalAudio),oi("audio",([r],[t])=>{var e,i;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((i=t==null?void 0:t.option)==null?void 0:i.microphoneId)}),re()],J.prototype,"startLocalAudio",1),y([Ae(_e.TRTC.updateLocalAudio),bi("audio"),re()],J.prototype,"updateLocalAudio",1),y([ni("audio"),re()],J.prototype,"stopLocalAudio",1),y([Ae(_e.TRTC.startLocalVideo),oi("video",([r],[t])=>{var e,i;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((i=t==null?void 0:t.option)==null?void 0:i.cameraId)}),re()],J.prototype,"startLocalVideo",1),y([Ae(_e.TRTC.updateLocalVideo),bi("video"),re()],J.prototype,"updateLocalVideo",1),y([ni("video"),re()],J.prototype,"stopLocalVideo",1),y([Ae(_e.TRTC.startScreenShare),oi("screen",()=>!0),re()],J.prototype,"startScreenShare",1),y([Ae(_e.TRTC.updateScreenShare),bi("screen"),re()],J.prototype,"updateScreenShare",1),y([re()],J.prototype,"stopScreenShare",1),y([Ae(_e.TRTC.startRemoteVideo),oi(r=>`v${r.userId}${r.streamType}`,()=>!0),re({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"startRemoteVideo",1),y([Ae(_e.TRTC.updateRemoteVideo),bi(r=>`v${r.userId}${r.streamType}`),re({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"updateRemoteVideo",1),y([Ae(_e.TRTC.stopRemoteVideo),G(r=>function(t){return p(this,null,function*(){if(t.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(i=>{this._remoteVideoConfigMap.has(`${i.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:i.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${i.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:i.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,t)})}),re({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"stopRemoteVideo",1),y([ni(r=>`v${r.userId}${r.streamType}`)],J.prototype,"_stopRemoteVideo",1),y([Ae(..._e.TRTC.muteRemoteAudio),re({getRemoteId:r=>r})],J.prototype,"muteRemoteAudio",1),y([Za(..._e.TRTC.setRemoteAudioVolume),cu(200,r=>r),re({getRemoteId:r=>r})],J.prototype,"setRemoteAudioVolume",1),y([$o("start"),oi((r,t)=>r.getAlias()+r.getGroup(t)),re({namePrefix:r=>r.getName()})],J.prototype,"startPlugin",1),y([$o("update"),bi((r,t)=>r.getAlias()+r.getGroup(t)),re({namePrefix:r=>r.getName()})],J.prototype,"updatePlugin",1),y([$o("stop"),ni((r,t)=>r.getAlias()+r.getGroup(t)),re({namePrefix:r=>r.getName()})],J.prototype,"stopPlugin",1),y([Za(..._e.TRTC.enableAudioVolumeEvaluation)],J.prototype,"enableAudioVolumeEvaluation",1),y([oi(r=>`a${r.userId}`,()=>!0)],J.prototype,"_startRemoteAudio",1),y([G(r=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(M(N({},t),{userId:e.userId})).catch(()=>{}))):r.call(this,t)})}),ni(r=>`a${r.userId}`)],J.prototype,"_stopRemoteAudio",1),y([ni("room")],J.prototype,"_exitRoom",1),y([ni("screen")],J.prototype,"_stopScreenShare",1),y([Ae(_e.TRTC.sendSEIMessage),Yd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],J.prototype,"sendSEIMessage",1),y([Ae(_e.TRTC.create)],J,"_create",1);var Es=J;var tc=class{constructor(){this._set=new Set;E.on(_.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let i=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(i)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let i=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(i)}getKey(t,e,i,s){return`${i}_${e}_${t}_${s}`}isJoined({userId:t,roomId:e,sdkAppId:i,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(t,e,i,s.useStringRoomId))}};function pm(){return p(this,null,function*(){let r,t;try{let m=yield ke();r=m&&m.length}catch(m){}try{let m=yield Ge();t=m&&m.length}catch(m){}let e={microphone:r,camera:t},{isH264EncodeSupported:i,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:i,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};X.uploadEvent({log:`trtcstats-${JSON.stringify(u)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(u)}`),X.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function hu(){return G(r=>{let t=new tc;return function(e,i,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=i,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new C({code:I.INVALID_OPERATION,message:D({key:O.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new C({code:I.INVALID_OPERATION,message:D({key:O.REPEAT_JOIN,data:this.userId})});t.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=ge.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))),X.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),pm.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Dt.isWebRTCSupported()||!a&&!c)throw new C({code:I.NOT_SUPPORTED,message:D({key:O.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!ge.getEnv()&&(yield this.schedule(o,s,Se));let u=yield r.call(this,e,i,s);return this.roomId=o,this._joinedTimestamp=ge.performanceNow(),E.emit(_.JOIN_SUCCESS,{room:this}),X.uploadEvent({log:`stat-conv-${Number(Ye)}-${location.hostname}`,userId:this.userId}),u}catch(u){throw t.delete({room:this,roomId:o}),E.emit(_.JOIN_FAILED,{room:this,error:u}),u}})}})}var mu=()=>G(r=>function(...t){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 pu(){return G(r=>function(...t){let e=r.apply(this,t);return t.forEach(i=>!i.isSubscribed&&i.subscribe(e)),e})}var fu=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},_u=[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 Go=new Set;function Eu(r){let t=[...Go.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return t||null}var Ts=class extends fu.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)-Go.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Go.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((i,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:I.JOIN_ROOM_FAILED,message:"join room timeout"}))},e)),this.once(ce.CONNECTED,()=>{clearTimeout(o),i()}),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(i){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(i){}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:i}=e.target,s=e.target===this._socketInUse;if(this._log.info(`websocket[${i} 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:i}=e.target;if(this._log.error(`websocket[${i}] 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 i=JSON.parse(e.data),{cmd:s,data:o}=i,n=Object.values(Tt),c=Object.keys(Tt)[n.indexOf(s)],u=B[c];switch(_u.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case Tt.CHANNEL_SETUP_RESULT:{if(i.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,this._signalInfo.tinyId=i.tinyId,o.svrTime&&wc(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:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:i.code,message:D({key:O.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i.code,errorMsg:i.message}})});this._log.error(`${i.code}, ${i.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:{i.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:i});break}case Tt.CHANNEL_RECONNECT_RESULT:{i.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, ${i.code} ${i.message}`),this.room.reJoin());break}default:this.emit(u,{data:i});break}}reconnect(e=h.MAIN){if(!this.room.isJoined&&this.keepAlive){this.close();return}if(this.isReconnecting)return;if(this._reconnectionCount>=Gr){this._log.warn(`SDK has tried reconnect signal channel for ${Gr} times, but all failed. please check your network`);let o=new C({code:I.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}/${Gr}]`);let i=this.getReconnectionUrl(e);this.emitConnectionStateChanged(Ve.CONNECTING),this._prevTime<0&&(this._prevTime=$()),e===h.MAIN?(this._socket=new WebSocket(i),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(i),this.bindSocket(this._backupSocket));let s=Fe(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 i=e===h.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&i.indexOf("&rc=1")===-1){let{roomId:s,useStringRoomId:o}=this.room;i+=`&rc=1&relayInnerIp=${this._signalInfo.relayInnerIp}&relayOuterIp=${this._signalInfo.relayIp}&relayPort=${this._signalInfo.relayPort}&roomId=${s}&useStringRoomId=${o}`}return i}send(e,i={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:i,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:i,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,u)=>{let l=setTimeout(()=>{this.off(o,m);let g=new C({code:I.API_CALL_TIMEOUT,message:D({key:O.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(g),u(g)},s),m=g=>{g.data.seq===f&&(clearTimeout(l),this.off(o,m),c(g))};this.on(o,m);let f=this.send(e,i)})}sendWaitForResponseWithRetry(e){let{commandDesc:i,command:s,retries:o=0,retryTimeout:n=0}=e;return ht({retryFunction:this.sendWaitForResponse,onRetrying:a=>{this._log.warn(`${i||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"),Go.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 i=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close()},e*1e3),s=o=>{o instanceof Ai&&o.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(i),this.room.off(P.STATECHANGED,s))};this.room.on(P.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 Tu=Ne(Me());var Is=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,i=[],s=0;for(let n=t;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(i.push(3),s=0),a==0?s++:s=0,i.push(a);break;default:s=0,i.push(a);break}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...i]).buffer);this.dataView=o}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,i=[],s=0;for(let n=t;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,i.push(this.dataView.getInt8(n));break;case 3:s!==2&&i.push(this.dataView.getInt8(n)),s=0;break;default:i.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...i]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)t+=255;else{t+=n;break}}let i=new ArrayBuffer(t),s=new DataView(i);for(let o=0;o<i.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var ic=class{constructor(t,e,i){this._connection=t;this._log=e;this._isUplink=i;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(t){this._mainVideoSenderOrReceiver=t;let e=t.createEncodedStreams(),i=e.readable,s=e.writable,o=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,i.pipeThrough(o).pipeTo(s,this._mainVideoAbortController).catch(()=>{})}restart(t){this.stop(),this.start(t)}stop(){var t;(t=this._mainVideoAbortController)==null||t.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach(t=>t.abort()),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let t=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(t),this._isUplink?t.getSenders().forEach((e,i)=>{if(i===1){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}}):t.getReceivers().forEach((e,i)=>{var s;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(i===1&&((s=e.track)==null?void 0:s.kind)===h.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))})}catch(t){this._log.warn(t)}}pipeSenderOrReceiver(t){let{readable:e,writable:i}=t.createEncodedStreams(),s=new AbortController;this._abortMap.set(t,s),e.pipeTo(i,s).catch(()=>{})}clearUnusedSenderOrReceiver(t){this._abortMap.forEach((e,i)=>{(this._isUplink?t.getSenders():t.getReceivers()).find(o=>o===i)||(e.abort(),this._abortMap.delete(i))})}push(t,e){e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t)}hasSEI(t){let e=new DataView(t);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(t){return t.type==="empty"||t.data.byteLength===0}getNaluCount(t){let e=0,i=0,s=new DataView(t);for(let o=0;o<t.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&i++,e=0;break;default:e=0;break}return i}encodeVideoFrame(t,e){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(t)){let i=this.getNaluCount(t.data),s=9-i;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+t.data.byteLength),c=new DataView(a),u=new DataView(t.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<t.data.byteLength;m++)c.setInt8(l++,u.getInt8(m));t.data=a,this._log.debug(`${o.length} sei sent`)}}catch(i){this._log.warn(i)}e.enqueue(t)}decodeVideoFrame(t,e){try{if(this._connection.isH264&&!this.isEmptyFrame(t)&&this.hasSEI(t.data)){let i=[],s=new DataView(t.data),o=0,n=-1,a=-1;for(let c=0;c<t.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,i.push(new Is(new DataView(s.buffer.slice(n,a)))),n=l,a=-1),!(s.getUint8(c+1)===6)){t.data=new DataView(s.buffer.slice(l)).buffer;break}}o=0}else o=0}this._log.debug(`${i.length} sei received`),j(this.onSEIMessage)&&i.reverse().forEach(c=>{this.onSEIMessage({seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer})})}}catch(i){this._log.warn(i)}e.enqueue(t)}encodeSEINalu(t){let e=t.byteLength,i=parseInt(e/255),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)o.push(255);o.push(s);let n=new DataView(t);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Is(new DataView(new Uint8Array(o).buffer),!0)}},Wo=ic;var rc=0,sc=!1,Ko=new Set,_m=r=>rc>2&&!sc&&Ko.size===0&&r,oc=!1,Ue=class{constructor(t){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 Tu.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=t.userId,this.tinyId=t.tinyId,this._room=t.room,this._sdpSemantics=t.room.sdpSemantics,this._isUplink=t.isUplink,this._log=A.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=t.signalChannel,this._enableSEI=t.enableSEI,this._enableSEI&&Zt&&(this._sei=new Wo(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=$())}afterConnect(t){return p(this,null,function*(){try{yield t,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 t={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(t),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(t){this._log.info("close connection"),this._emitter.emit("closed",t),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),Ko.delete(this)}closePeerConnection(t=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,t&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new C({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qe;let t=null;if(this._isUplink){if(!rr()||this._peerConnection.getSenders().length===0)return Qe;t=this._peerConnection.getSenders()[0].transport}else{if(!gi()||this._peerConnection.getReceivers().length===0)return Qe;t=this._peerConnection.getReceivers()[0].transport}return t?t.state:Qe}onConnectionStateChange(t){let e=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info(`connectionState: ${t.target.connectionState}, ICE: ${e}, DTLS: ${i}`),t.target.connectionState===te.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),t.target.connectionState===te.FAILED||t.target.connectionState===te.CLOSED){let s=`connection ${t.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${i}`,o=new C({message:s,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(t.target.connectionState===te.CONNECTED||t.target.connectionState===te.COMPLETED)&&(this.logSelectedCandidate(),X.logSuccessEvent({userId:this._room.userId,eventType:be.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(t){return t===this._currentState?!1:(t==="CONNECTED"?(rc=0,sc=!1,oc=!0,Ko.add(this)):Ko.delete(this),E.emit(_.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:t,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:t}),this._currentState=t,!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 t=yield this._peerConnection.getStats();for(let[,e]of t)if(zt(e)){let i=t.get(e.localCandidateId),s=t.get(e.remoteCandidateId);i&&(this._log.info(`local candidate: ${i.candidateType} ${i.protocol}:${i.ip||i.address}:${i.port} ${i.networkType||""} ${i.candidateType==="relay"?`relayProtocol:${i.relayProtocol}`:""}`),this._localAddress=`${i.ip||i.address}:${i.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((t,e)=>{if(this._currentState==="CONNECTED")return t();this._waitForPeerConnectionConnectedPromiseReject=e;let i=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),t())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new C({code:I.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",i,this)},n=setTimeout(()=>{o();let a=new C({code:I.API_CALL_TIMEOUT,message:"connection timeout"});rc+=1,_m(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),sc=!0,this._emitter.emit("firewall-restriction")),e(a)},Wr);E.on(_.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",i,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 t=new C({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?O.UPLINK_RECONNECTION_FAILED:O.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",t),-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(t,e,i){this._emitter.on(t,e,i)}off(t,e,i){this._emitter.off(t,e,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var t,e;return!!((e=(t=this._peerConnection)==null?void 0:t.remoteDescription)!=null&&e.sdp.includes("H264"))}};var dc=Ne(cc());var ue=function(r){return dc.default.parse(r)},We=function(r){return dc.default.write(r)},yu=function(r){let t=ue(r);return t.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}),We(t)};function bu(r){let t=ue(r);return t.media.forEach(e=>{var i,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=(i=e.rtcpFb)==null?void 0:i.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(t)}function Jo(r){return Object.keys(r).filter(t=>r[t])}var lc=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 ar(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 Xt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var i,s,o;e!==this._flag&&(this._flag=e,(i=this.remoteAudioTrack)==null||i.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 i=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&i!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:i,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:i,state:e})),s}onTrack(e){let i=e.streams[0],{track:s}=e,o=i.id===Fr?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 i=e.split(`\r
33
- `),s=new Map;i.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&i[a+1]&&!/^a=rtcp-fb:/.test(i[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];i.splice(a+n,0,c)}return i.join(`\r
34
- `)}addSPSDescription(e){let i=ue(e);return i.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),We(i)}removeSDESDescription(e){let i=["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=>!i.includes(n.uri)))}),We(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,i){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 ${i} ${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(i)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new C({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:i}){if(this._currentState==="CONNECTED"&&(i==="main"&&!this.isMainStreamSubscribed||i==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${i} 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"} ${i} [${Jo(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,i=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:i.audio,bigVideo:i.video,auxVideo:i.auxiliary,smallVideo:i.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(i){throw this.closePeerConnection(!0),i}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:i,sdp:s}=this._peerConnection.localDescription,o={type:i,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:kn});if(!this._peerConnection){let a=new C({code:I.INVALID_OPERATION,message:D({key:O.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(i){throw this._isSDPExchanging=!1,i}})}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 i=yield this._peerConnection.createOffer(e);if(i.sdp){let{isH264DecodeSupported:s}=yield po();s||(this._log.warn("remove h264 desc from sdp"),i.sdp=bu(i.sdp)),i.sdp=this.addRRTRLine(i.sdp),i.sdp=this.addSPSDescription(i.sdp),i.sdp=yu(i.sdp),this._sdpSemantics===jt&&(i.sdp=this.removeSDESDescription(i.sdp))}yield this._peerConnection.setLocalDescription(i)})}onSubscribeResult(e){return p(this,null,function*(){let{code:i,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(i===Ei)throw new C({code:I.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264DECODE})});try{if(i!==0)throw new C({code:i,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(Fr)});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(Fr)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Dn)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(i){}}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(lc.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(i){let s=Fe(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:i}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=i}},gs=lc;y([G(r=>function(...t){return new Promise((e,i)=>{let s=o=>{this._emitter.off("closed",s),i(new C({code:I.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,t).then(e,i).finally(()=>{this._emitter.off("closed",s)})})})],gs.prototype,"subscribe",1),y([Ao(Ue.prototype.afterConnect),go(Ue.prototype.beforeConnect)],gs.prototype,"connect",1);var uc=gs;var Du={voiceActivityDetection:!1},hc=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 i,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=!!((i=a[0])!=null&&i.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,i){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(i?i.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:i,isAuxiliary:s}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),i&&(this._publishingLocalVideoTrack=i),this._isPublishingAux=s;let n;i&&!s&&i.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),et()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:i,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:i,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(i&&(this.localAuxVideoTrack=i),e&&(this.localAuxAudioTrack=e)):(i&&(this.localMainVideoTrack=i),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,i),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:i,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=i==null?void 0:i.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:i.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:i.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(K.SENDONLY,m),yield this.doPublishChange(),i==null||i.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),i==null||i.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:i,smallTrack:s}){this._log.info("publish by addtrack");let n=i==null?void 0:i.outMediaTrack,a=this._audioManager.mixedAudioTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){a&&(yield this.addTrack(e)),n&&(yield this.addTrack(i));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(i=>{i&&(i==null||i.on("mute",this.sendMutedFlag,this),i==null||i.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(i=>{i&&(i==null||i.off("mute",this.sendMutedFlag,this),i==null||i.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:i}){if(!mt()){if(e&&e.outMediaTrack&&!i&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(i&&i.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(i),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,i),this.emitConnectionStateChangedEvent("DISCONNECTED",i);return}let o=i&&i===this.localAuxVideoTrack,n=i==null?void 0:i.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,i),i==null||i.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let i={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:i,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(i=>{if(i.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw i})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:i}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":i&&(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 i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${i?h.AUXILIARY:h.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),et()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,i){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=i?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 i=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",i));let s=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===i.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=i.kind===h.VIDEO?i:this._audioManager.mixedAudioTrack;if(o&&this._peerConnection.addTrack(i,new MediaStream([o])),i.kind===h.VIDEO&&e instanceof Le&&e.small){let n=new MediaStream,a=this._room.videoManager.smallTrack;n.addTrack(a),this._peerConnection.addTrack(a,n)}yield this.updateOffer("add",i)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Yi||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,i=ue(e);for(let s=0;s<i.media.length;s++)if(Number(i.media[s].mid)===0&&i.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let i=null;mt()&&(i=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),i&&j(i.stop)&&(this._log.info("stop transceiver"),i.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${i?h.AUXILIARY:h.MAIN} stream`),et()?yield this.removeTrackByTransceiver(e,i):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,i){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=i?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,i){return p(this,null,function*(){if(!Q)return;let s=!1,o=!1;this._log.info(`setting transceiver ${i.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(i.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
35
- `).map(u=>{if(u.match(new RegExp(`a=(${K.INACTIVE}|${K.RECVONLY}|${K.SENDONLY})`))&&a++,i.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
36
- `);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 i=this._peerConnection.getSenders().find(s=>s.track===e.outMediaTrack);i&&(this.removeSender(i),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 i=(n=this._peerConnection)==null?void 0:n.getSenders();if(!i||i.length===0||!e.mediaTrack)return;let s;if(et()?s=e.kind===h.AUDIO?i[0]:i[1]:s=i.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?i[3]&&(yield i[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack))})}updateOffer(e,i){return p(this,null,function*(){try{let s=yield this._peerConnection.createOffer(Du);Q&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let o=this.updateMediaSettings(),n={action:e,trackId:i.id,kind:i.kind===h.VIDEO?"bigVideo":i.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:Pn,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:i,videoType:s,sdp:o}){if(!ts())return o?i===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e):void 0;let a=0;i===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||""}${i} bandwidth ${e} kbps`),o}catch(l){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${l}`),o)return i===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,i,s){let o="AS";Q&&(o="TIAS",i=i*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}:${i}\r
37
- `:c)),e}updateAudioBandwidthRestriction(e,i){let s="AS";return Q&&(s="TIAS",i=i*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
32
+ ${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-beta.2";function Ce(...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)&&Ai(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)})}},vi=ps;d(vi,"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(vi,"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(vi,"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()})}},ki=_s;d(ki,"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(ki,"updateValidateRule",{type:"object"}),d(ki,"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 vi(Uo(this._room));this._plugins.set(s.getName(),s);let o=new ki(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 ar()).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 ar())[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}):ar().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(Ne=>m[Ne.uint32_video_stream_type]).map(Ne=>({bitrate:(Ne.uint32_video_codec_bitrate||0)/1e3,width:Ne.uint32_video_width,height:Ne.uint32_video_height,frameRate:Ne.uint32_video_enc_fps,videoType:m[Ne.uint32_video_stream_type]}))},remoteStatistics:l.msg_down_stream_info.map(Ne=>({userId:Ne.msg_user_info.str_identifier,audio:{bitrate:(Ne.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(Ne.msg_audio_status.uint32_audio_level||0)/Xe},video:Ne.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 ke(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 Me(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 ar()}static setCurrentSpeaker(e){return p(this,null,function*(){(yield ar()).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([Ce(_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([Ce(_e.TRTC.switchRole),Di("room",{merge:(r,i)=>i}),se()],J.prototype,"switchRole",1),y([se()],J.prototype,"destroy",1),y([Ce(_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([Ce(_e.TRTC.updateLocalAudio),Di("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([Ce(_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([Ce(_e.TRTC.updateLocalVideo),Di("video"),se()],J.prototype,"updateLocalVideo",1),y([ni("video"),se()],J.prototype,"stopLocalVideo",1),y([Ce(_e.TRTC.startScreenShare),oi("screen",()=>!0),se()],J.prototype,"startScreenShare",1),y([Ce(_e.TRTC.updateScreenShare),Di("screen"),se()],J.prototype,"updateScreenShare",1),y([se()],J.prototype,"stopScreenShare",1),y([Ce(_e.TRTC.startRemoteVideo),oi(r=>`v${r.userId}${r.streamType}`,()=>!0),se({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"startRemoteVideo",1),y([Ce(_e.TRTC.updateRemoteVideo),Di(r=>`v${r.userId}${r.streamType}`),se({getRemoteId:r=>`${r.userId}_${r.streamType}`})],J.prototype,"updateRemoteVideo",1),y([Ce(_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([Ce(..._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"),Di((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([Ce(_e.TRTC.sendSEIMessage),Yd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],J.prototype,"sendSEIMessage",1),y([Ce(_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=Re.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&&!Re.getEnv()&&(yield this.schedule(o,s,Ae));let u=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=Re.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=ye(Le());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 Ci&&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=ye(Le());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(!or()||this._peerConnection.getSenders().length===0)return qe;i=this._peerConnection.getSenders()[0].transport}else{if(!Ri()||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:Oe.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=ye(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 dr(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
33
+ `),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
34
+ `)}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===Ti)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 Me&&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
35
+ `).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
36
+ `);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
37
+ `: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
38
38
  c=IN $2\r
39
- b=${s}:${i}\r
40
- `),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(Du);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(i=>{let{code:s,message:o,data:n}=i.data;return s===0?this.acceptAnswer(n):this.checkPublishResultCode(s,o)})}setSDPDirection(e,i,s="all"){let o=ue(e);return o.media.forEach(n=>{(s==="all"||n.type===s)&&(n.direction=i)}),We(o)}acceptAnswer(e){return p(this,null,function*(){var i,s,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((i=this._publishingLocalVideoTrack)==null?void 0:i.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 g=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:g})}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(hc.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(i){let s=Fe(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===Yi&&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(i){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let i=this._peerConnection.getSenders();if(e===h.AUXILIARY&&i[3]&&i[3].track)return i[3].track.id;if(e===h.VIDEO&&i[1]&&i[1].track)return i[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let i=this.localMainVideoTrack.mediaTrack;if(i)return i.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let i=this.localAuxVideoTrack.mediaTrack;if(i)return i.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,i){if(e!==0)throw e===Ei?(this._log.error(me.NOT_SUPPORTED_H264ENCODE),new C({code:I.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264ENCODE})})):new C({code:I.UNKNOWN,message:D({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.PUBLISH_RESULT,code:e,message:i}})})}sendSEI(e,i){var s;(s=this._sei)==null||s.push(e,i)}},As=hc;y([G(r=>function(...t){return new Promise((e,i)=>{let s=o=>{this._emitter.off("closed",s),i(new C({code:I.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,t).then(e,i).finally(()=>{this._emitter.off("closed",s)})})})],As.prototype,"publish",1),y([Ao(Ue.prototype.afterConnect),go(Ue.prototype.beforeConnect)],As.prototype,"connect",1);var jo=As;var Rs=class{constructor(t,e){this.room=t;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(t){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},i=t.getPeerConnection(),s=t.getSSRC();if(i)try{if((this._spcStats||(yield i.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=t.localMainVideoTrack):n.ssrc===s.small?c=h.SMALL:n.ssrc===s.auxiliary&&(u=t.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===t.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=n.framesPerSecond:n.trackIdentifier===t.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===t.getVideoTrackId(h.VIDEO)||n.ssrc===s.video?a=h.VIDEO:(n.trackIdentifier===t.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}}),t.localMainAudioTrack){let n=t.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(t){return p(this,null,function*(){let e={tinyId:t.tinyId,userId:t.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}},i=t.getPeerConnection();if(i)try{let{ssrc:s}=t,{muteState:o,subscribeState:n}=t;(this._spcStats||(yield i.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}=t;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(Q&&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=t.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=t.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===t.getMainStreamVideoTrackId()||c.ssrc===s.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,t.remoteVideoTrack.stat.frameWidth=c.frameWidth,t.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===t.getAuxStreamVideoTrackId()||c.ssrc===s.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,t.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,t.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=t.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(t,e){return p(this,null,function*(){let i={},s=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:i,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}t&&(i=yield this.getSenderStats(t));for(let[o,n]of e){let a=yield this.getReceiverStats(n);s.push(a)}return{senderStats:i,receiverStats:s}})}getDifferenceValue(t,e){if(kt(t))return e;let i=e-t;return i<0?0:i}prepareReport({stats:t,report:e,freezeMap:i}){if(!kt(t.senderStats)){let l={uint32_audio_level:t.senderStats.audio.audioLevel*qe,uint32_audio_energy:t.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(l.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*qe);let m=[];if(t.senderStats.video.bytesSent){let g={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:(t.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(t.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};m.push(g)}if(t.senderStats.small.bytesSent){let g={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:(t.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(t.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};m.push(g)}if(t.senderStats.auxiliary.bytesSent){let g={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:(t.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(t.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};m.push(g)}let f={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.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=[],t.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=i.get(`${l.userId}_${vn}`),g=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:g,uint32_video_dec_fps:l.video.framesDecoded};m.msg_video_status.push(b)}if(l.hasAuxiliary){let f=i.get(`${l.userId}_${Ln}`),g=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:g,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(se=>se.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,g=0,b=0;m&&l.uint32_video_codec_bitrate>=m.uint32_video_codec_bitrate&&(f=m.uint32_video_codec_bitrate,g=m.uint32_video_enc_fps,b=m.uint32_video_codec_fps);let L=this.getDifferenceValue(f,l.uint32_video_codec_bitrate);l.uint32_video_codec_bitrate=Math.round(L*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(g,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(!kt(l.msg_audio_status)&&!kt(m.msg_audio_status)){let f=l.msg_audio_status,g=m.msg_audio_status;f.uint32_audio_origin_lost=this.getDifferenceValue(g.uint32_audio_origin_lost,f.uint32_audio_origin_lost),f.uint32_audio_receive=this.getDifferenceValue(g.uint32_audio_receive,f.uint32_audio_receive),f.uint32_audio_receive+=f.uint32_audio_origin_lost;let b=this.getDifferenceValue(g.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(L=>L.uint32_video_stream_type===b.uint32_video_stream_type)),l.msg_video_status.forEach(b=>{let L=f.find(tl=>tl.uint32_video_stream_type===b.uint32_video_stream_type),se=L.uint32_video_receive,Re=L.uint32_video_origin_lost,ui=L.uint32_video_codec_bitrate,li=L.uint32_video_receive_fps,Ce=L.uint32_video_dec_fps;b.uint32_video_origin_lost=this.getDifferenceValue(Re,b.uint32_video_origin_lost),b.uint32_video_receive=this.getDifferenceValue(se,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 el=this.getDifferenceValue(li,b.uint32_video_receive_fps);b.uint32_video_receive_fps=Math.round(el/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:t,downlinkConnections:e,freezeMap:i}){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(t,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:i}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var vu=Ne(Me());var mc=class extends vu.default{constructor({signalChannel:e,room:i}){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=i,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:i,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${i}, 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 i=e.data.data;if(i.delay&&this.updateDelay(i.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=i.expectAudPkg+i.expectVidPkg,n=i.recvAudPkg+i.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/o*100),this._uplinkRTT=i.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()],i=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<i.length;a++){let c=i[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,g=this._downlinkPrevStatMap.get(c),b=l-g.totalPacketsLost,L=m-g.totalPacketsReceived;b<=0||L<0?f=0:f=Math.round(b/(b+L)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:u,loss:f,userId:i[a].getUserId(),audioDelay:i[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:i[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 i={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!gi())return i;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)&&(i.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===h.AUDIO||c.mediaType===h.VIDEO)&&(i.totalPacketsLost+=c.packetsLost,i.totalPacketsReceived+=c.packetsReceived)});return i}catch(o){return i}})}getAverageLossAndRTT(e){let i={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{i.rtt+=s.rtt,i.loss+=s.loss}),Object.keys(i).forEach(s=>{i[s]=Math.round(i[s]/e.length)})),i}getNetworkQuality(e,i){return e>50||i>500?5:e>30||i>350?4:e>20||i>200?3:e>10||i>100?2:e>=0||i>=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=ee.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(mc.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&&(ee.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:i}=this._room;e.forEach(({srcTinyId:s,videoDelay:o,audioDelay:n})=>{let a=i.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}},Li=mc;d(Li,"EVENT_NETWORK_QUALITY","0");var Ft=new WeakMap;function _r({settings:r={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:i}){return function(s,o,n){let a=ht({retryFunction:n.value,settings:r,onError({error:c,retry:u,reject:l,retryFuncArgs:m}){t&&t.call(this,c,()=>{var f;(f=Ft.get(s))!=null&&f.has(o)?u():l(c)},l,m)},onRetrying:(c,u)=>{var l;j(e)&&e(c,u),(l=Ft.get(s))!=null&&l.has(o)&&(Ft.get(s).get(o).stopRetry=u)},onRetryFailed:i});return n.value=function(...c){let u=Ft.get(s);return u?u.set(o,{args:c}):Ft.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=Ft.get(s))==null?void 0:l.delete(o)})},n}}function Cs({fnName:r,callback:t,validateArgs:e=!0}){return function(i,s,o){let n=o.value;return o.value=function(...a){var c,u;if((c=Ft.get(i))!=null&&c.has(r)){let{stopRetry:l,args:m}=Ft.get(i).get(r),f=!0;if(e){for(let g of m)if(!a.find(b=>b===g)){f=!1;break}}f&&(t&&t.apply(this,a),l&&l(),(u=Ft.get(i))==null||u.delete(r))}return n.apply(this,a)},o}}function ym({fn:r,context:t}){return function(...e){try{let i=r.apply(t,e);return Xr(i)?i.catch(s=>A.error(`${r.name}() error observed ${s}`)):i}catch(i){A.error(`${r.name}() error observed ${i}`)}}}var Yo=class{constructor(t){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._apiSuccessRateMap=new Map;this._eventMap=new Map;this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=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]=ym({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=ee.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:Se,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(),Ur().then(t=>{this._basicInfo.string_os_version=gn(),t&&(this._basicInfo.string_device_name=t.model)})}addEvent(t,e){return this._eventMap.set(t,e),E.on(t,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:t,state:e,type:i})=>{!Yt(t)||!this.hitTest(t.room)||e==="PLAYING"&&(i===h.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(_.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(_.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(_.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(_.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:i})=>{if(!this.hitTest(t))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=i.hasAudio||i.hasVideo||i.hasSmall,a=i.hasAuxiliary;!s&&n&&this.handleRemoteStreamAdded(i.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(i.userId,"auxiliary")}).addEvent(_.API_SUCCESS_RATE,this.handleAPISuccessRate).addEvent(_.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((t,e)=>E.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),ee.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),t.params&&(T(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),T(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:i,local:s,dns:o,tcp:n,tls:a,request:c,response:u}=e;this._pathJoinRoom.int32_schedule_cost=i,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:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof C?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var s;let i=`${t}_${e}`;if(!this._remoteStreamStatMap.has(i)){let o={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:M(N({},bm),{msg_user_info:new Ns({userId:t,tinyId:(s=this._room.remotePublishedUserMap.get(t))==null?void 0:s.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(i,o)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:i,subscribeState:s}){if(!this.hitTest(t))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}_${i}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=u),i==="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:t,remotePublishedUser:e,streamType:i}){if(this.hitTest(t)){let s=`${e.userId}_${i}`,o=this._remoteStreamStatMap.get(s);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!Yt(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,i=this._remoteStreamStatMap.get(e);(i==null?void 0:i.playStreamTime)===0&&(i.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!Yt(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,i=this._pathMainVideoMap.get(e);i&&i.statsToReport.uint64_combine_first_frame_time===0&&(i.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,i=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=i),o)){let{statsToReport:a,playStreamTime:c,subscribedTime:u}=o;a.uint32_video_render_first===0&&c-u<=100&&(a.uint32_video_render_first=i-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=i-n.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,i=this._pathMainAudioMap.get(e);i&&i.statsToReport.uint64_play_first_frame_time===0&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:i,userId:s,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=i,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:i,count:1,totalAudioDelay:c,totalVideoDelay:u,audioDelayCount:m,videoDelayCount:l})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_up_stream_info:e,msg_down_stream_info:i}=t.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/qe*100)>0&&(this._localStreamStat.totalAudioLevel+=s/qe,this._localStreamStat.audioLevelCount++)}i.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,g=`${c}_${m?"main":"auxiliary"}`,b=this._remoteStreamStatMap.get(g);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 L=m?u.remoteVideoTrack:u.remoteAuxiliaryTrack;L.stat.jitterBufferDelay&&(b.videoJitterBufferDelay=L.stat.jitterBufferDelay),L.stat.framesReceived&&(b.statsToReport.uint32_video_consume_render_rate=Math.floor(L.stat.framesDecoded/L.stat.framesReceived*Ls(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/qe*100)>0&&(m.totalAudioLevel+=n.uint32_audio_level/qe,m.audioLevelCount++))}})}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let 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():I.UNKNOWN);t.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()),t.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:t,apiName:e,error:i,cost:s}){if(!this.hitTest(t))return;let o=Lu[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(i){let c=i.extraCode||i.code||I.UNKNOWN;X.logFailedEvent({eventType:e,code:c,userId:this._room.userId,error:i});let u={int32_error_code:c,error_count:1};n.msg_error_code.push(u)}else q(s)&&(X.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(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Ji)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ji)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Hr)>=0}hitTest(t){return t===this._room}checkStorage(){return p(this,null,function*(){try{let t=ir.getItem(this._storageKey);t&&(yield this.upload(t),ir.deleteItem(this._storageKey))}catch(t){this._log.warn(t)}})}setStorage(){this.prepareReport();let t=this.getReportData();t.msg_path_enter_room.uint64_start_time!==0&&ir.setItem(this._storageKey,t)}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 t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:i}=t,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(s){let{totalLoss:l,count:m,audioDelayCount:f,videoDelayCount:g,totalAudioDelay:b,totalVideoDelay:L}=s;t.statsToReport.uint32_avg_down_loss=Math.floor(l/m),f&&b&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(b/f),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),g&&L&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(L/g))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(t.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),t.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Mi);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:u}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=c,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(u,t.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Mi&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Mi)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Mi&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Mi)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Mi&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Mi)}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 t=this.getReportData();this.upload(t),ir.deleteItem(this._storageKey),this.initData()}catch(t){this._log.warn(t)}}upload(t){if(Ye||t.msg_path_enter_room.uint64_start_time===0||[zs,Rn,Cn].findIndex(o=>o===location.host)>=0)return;let e=Number(this._room.sdkAppId),i=Ii(e,fi.KEY_POINT),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(i,JSON.stringify(t))),s||Qt({url:i,body:JSON.stringify(t)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}};y([_r({settings:{timeout:500,retries:3}})],Yo.prototype,"upload",1);var Mi=5e3,bm={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(t){this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Lu=(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))(Lu||{}),Mu=Yo;var pc=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}},fr=pc;var _c=class{constructor(t){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=t.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:t,prevMuteState:e,muteState:i})=>{var n;let{userId:s}=i;if(!this.hitTest(t))return;e.hasAudio&&!i.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,h.AUDIO),e.hasVideo&&!i.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!i.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!o||(!e.hasAudio&&i.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&i.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&i.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>E.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>E.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:i}){if(!this.hitTest(t))return;let{userId:s}=i,o=`${s}_${e}`;if(i.muteState.hasAudio&&e==="main")if(i.remoteAudioTrack.isSubscribed){let n=new fr,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(i.muteState.hasVideo||i.muteState.hasAuxiliary)if(i.remoteVideoTrack.isSubscribed||i.remoteAuxiliaryTrack.isSubscribed){let n=new fr,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:t,streamType:e,remotePublishedUser:i}){if(!this.hitTest(t))return;let{userId:s}=i,o=`${s}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,i){let s=`${t}_${i}`,o=new fr,n=this._durationMap.get(s);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(s,{userId:t,type:i,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let s=this._durationMap.get(t)[e].find(o=>o.endTime===0);s&&s.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((s,o)=>s+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Pu=_c;var fc=class{constructor(t){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=t.room,this.installEvents()}installEvents(){this._eventMap.set(_.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(_.PLAY_TRACK_START,this.onPlayTrackStart).set(_.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:i})=>{if(!this.hitTest(t))return;let{userId:s}=i,o=`${s}_${e}`;this.stopDataFreeze({key:o,userId:s,type:e})}).set(_.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:i})=>{if(!this.hitTest(t))return;let{userId:s}=i;if(e.hasVideo&&!i.hasVideo){let o="main",n=`${i.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}if(e.hasAuxiliary&&!i.hasAuxiliary){let o="auxiliary",n=`${i.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}}).set(_.PLAYER_STATE_CHANGED,({track:t,state:e,reason:i,type:s})=>{if(!(!Yt(t)||!this.hitTest(t.room)||s!==h.VIDEO)){if(e==="PLAYING"){let o=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}i===h.MUTE?this.onVideoTrackMuted(t):i===h.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(_.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>E.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>E.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:i}=t,s=`${e}_${i}`,o=this._dataFreezeMap.get(s),n=new fr;o?o.durationItemList.push(n):this._dataFreezeMap.set(s,{userId:e,type:i,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:i}=t,s=`${e}_${i}`;this.stopDataFreeze({key:s,userId:e,type:i})}onHearBeatReport({room:t,report:e}){!this.hitTest(t)||e.msg_down_stream_info.forEach(i=>{let s=this._room.remotePublishedUserMap.get(i.msg_user_info.str_identifier);if(!s)return;let{userId:o,muteState:n}=s;i.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:t,userId:e,type:i}){let s=this._dataFreezeMap.get(t);if(!s||!s.isFreezing())return;let o=s.durationItemList[s.durationItemList.length-1];o.stop();let n=o.getDuration();n>oo?this._monitorFreezeData.set(t,{userId:e,type:i,duration:n}):s.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,i)=>{let s=i.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return p(this,arguments,function*({userId:t,fps:e,type:i}){let o=`${t}_${i}`,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:t,type:i,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:t}){if(!Yt(t)||!this.hitTest(t.room)||t.kind!==h.VIDEO||t.hasFlag)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},i=this._dataFreezeMap.get(t);if(i){if(i.isFreezing()){let s=i.durationItemList[i.durationItemList.length-1];s.stop(),s.getDuration()<oo&&i.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(i.durationItemList),e.count=i.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),i=0,s=0;if(e)if(!e.isFreeze)i=e.renderFreezeTotal;else{let o=$(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;i=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:i,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},ku=fc;var Ec=null,Tc=!0;function ci(r){ie(r)&&r!==Tc&&(Tc=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 Om(r,t,e){let i=performance.getEntriesByType("resource"),s=Qo(r,h.MAIN),o=Qo(r,h.BACKUP),n={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of i)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),g=Math.round(a.secureConnectionStart-a.connectStart),b=Math.round(a.responseStart-a.requestStart),L=Math.round(a.responseEnd-a.responseStart),se=[l,m,f,g,b,L];X.uploadEvent({log:`stat-schedule-net:${u}(${se.join("->")}) ${c}`,userId:t}),n=M(N({},n),{totalCost:u,local:l,dns:m,tcp:g,tls:f,request:b,response:L});break}return n}function wu(a){return p(this,arguments,function*({userId:r,sdkAppId:t,useStringRoomId:e,roomId:i,userSig:s,version:o,frameWorkType:n}){if(!Tc&&Ec)return{isCached:!0,result:Ec};let c={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(r)),u.append("sdkAppId",String(t)),u.append("isStrGroupId",String(e)),u.append("groupId",String(i)),u.append("sdkVersion",o),u.append("userSig",String(s)),u.append("frameWorkType",String(n));let l=$(),m=yield vm(u,c,t);m.config&&(m.config.loggerDomain&&_i(m.config.loggerDomain),ie(m.config.scheduleCache)&&ci(!m.config.scheduleCache)),c.delta=$()-l;let f=Om(Number(t),r,l);return Ec=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}`:""}`,g=new C({code:I.SCHEDULE_FAILED,extraCode:m,message:D({key:O.JOIN_ROOM_FAILED,data:{error:f,code:m}})});throw A.error(g),g}})}var Xo={main:"",backup:""};function Ic(r){de(r)?(Xo.main=r[0],Xo.backup=r[1]):Xo.main=r}function Qo(r,t=h.MAIN){let e;return ao(r)?e=t===h.MAIN?Xi.MAIN_OVERSEA:Xi.BACKUP_OVERSEA:e=t===h.MAIN?Xi.MAIN:Xi.BACKUP,`https://${Xo[t]||e}/api/v1/config`}function Dm(r,t,e){return new Promise((i,s)=>{Qt({url:r,body:t,timeout:e.timeout}).then(o=>{o.data.code===0?i(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var xu=(r,t)=>ht({retryFunction:Dm,settings:{retries:3,timeout:0},onError:t,onRetrying:r});function vm(r,t,e){return new Promise((i,s)=>{let o=null;Bn([xu(n=>t.count[0]=n+1,({error:n,retry:a})=>{t.msg[0]=n.message,o||a()})(Qo(e,h.MAIN),r,{get timeout(){return Zi(2+t.count[0])*1e3}}),xu(n=>t.count[1]=n+1,({error:n,retry:a})=>{t.msg[1]=n.message,o||a()})(Qo(e,h.BACKUP),r,{get timeout(){return Zi(2+t.count[1])*1e3}})]).then(n=>{o=n,i(o)}).catch(s)})}var Vu=Ne(Me(),1);var Lm=[-1,-1,-1,1,1,-1,1,1],Mm=[0,0,0,1,1,0,1,1],Be=class extends P{constructor(e,i){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=i.name,this.matchInputSize=i.matchInputSize!==!1,this.width=i.width||e.width,this.height=i.height||e.height;let s=e._gl;if(!s){if(e.ctx2d&&i.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{i.createTexture!==!1&&(this.texture=s.createTexture()),this.texCoordBuffer=this.createBuffer(Mm),this.positionBuffer=this.createBuffer(Lm),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)}),i.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)})})),i.useDefaultProgram&&(this.program=this.context.defaultProgam),i.vertexShaderSource&&i.fragmentShaderSource&&(this.vertexShader=e.createShader(s.VERTEX_SHADER,i.vertexShaderSource),this.fragmentShader=e.createShader(s.FRAGMENT_SHADER,i.fragmentShaderSource),this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(`${this.name} init failed`,o)}}connect(e,...i){return e.addInput(this,...i),this.output=e,e}addInput(e,...i){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 i;return(i=this.input)!=null&&i.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}disconnect(...e){var i;(i=this.output)==null||i.removeInput(this,...e),delete this.output}removeInput(e,...i){delete this.input}close(){var i,s;(i=this.output)==null||i.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,i){this.texture&&this.context.useTexture(this.texture,e,i)}useInputTexture(e,i){this.context.useTexture(this.input.texture,e,i)}useProgram(){this.context._gl.useProgram(this.program)}useBufferFrame(e){let i=this.context._gl;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo),e(),i.bindFramebuffer(i.FRAMEBUFFER,null)}createBuffer(e){let i=this.context._gl,s=i.createBuffer();return i.bindBuffer(i.ARRAY_BUFFER,s),i.bufferData(i.ARRAY_BUFFER,new Float32Array(e),i.STATIC_DRAW),s}setTexBuffer(e){let i=this.context._gl,s=this.texCoordBuffer;i.bindBuffer(i.ARRAY_BUFFER,s),i.bufferData(i.ARRAY_BUFFER,new Float32Array(e),i.STATIC_DRAW)}setPosBuffer(e){let i=this.context._gl,s=this.positionBuffer;i.bindBuffer(i.ARRAY_BUFFER,s),i.bufferData(i.ARRAY_BUFFER,new Float32Array(e),i.STATIC_DRAW)}changeBufferData(e,i){let s=this.context._gl;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(i),s.STATIC_DRAW)}setAttributes(e){let i=this.context._gl;for(let s in e){let o=i.getAttribLocation(this.program,s);i.bindBuffer(i.ARRAY_BUFFER,e[s]),i.enableVertexAttribArray(o),i.vertexAttribPointer(o,2,i.FLOAT,!1,0,0)}}getVertexPoint(e,i){return[e/this.width*2-1,i/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,i){this.width===e&&this.height===i||(this.width=e,this.height=i,this._canvas&&(this._canvas.width=e,this._canvas.height=i),this.texture&&this.fbo&&this.useTexture(s=>s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,i,0,s.RGBA,s.UNSIGNED_BYTE,null)),this.output&&this.output.matchInputSize&&this.output.resize(e,i))}draw2d(e,i,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,i,s):this.ctx2d.drawImage(e,i,s,o,n),!0):!1}getInfo(){var u;let{totalFrames:e,x:i,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:i,y:s,width:o,height:n,timestamp:a,fps:c},N({parent:(u=this.input)==null?void 0:u.getInfo()},this.lastInfo)}};y([Z(P.INIT,"connected")],Be.prototype,"connect",1),y([Z("connected",P.INIT,{ignoreError:!0})],Be.prototype,"disconnect",1),y([Z([],"closed")],Be.prototype,"close",1);var Pm=[0,1,0,0,1,1,1,0],Sc=class extends Be{constructor(e,i){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},i));d(this,"_intervalId",0);d(this,"_sequence",0);e._gl?this.setTexBuffer(Pm):e.ctx2d&&(this.ctx2d=e.ctx2d)}start(e){this._intervalId=ee.run("intervalInWorker",()=>{e!==this.context.frameRate&&(ee.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++);let i=this.context._gl;i&&i.getError()!==i.NO_ERROR&&this.context.destroy(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i.getError()}`)},{fps:this.context.frameRate})}render(e){var i;return(i=this.input)!=null&&i.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,...i){super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),ee.clearTask(this._intervalId)}},ys=class extends Sc{constructor(e,i){super(e,i);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,i){super.resize(e,i),this.context.setSize(e,i)}};var qo=class extends ys{constructor(e,i){super(e,{name:"smallDestination"});this.resolution=i}resize(e,i){let s,o=e*i,n=this.resolution.width*this.resolution.height;A.info(`big res: ${e}*${i} 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} * ${i} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),i/Math.sqrt(s))}};var bs=class extends Be{constructor(e,i){super(e,{name:"imageSource"});this.image=i;d(this,"_image");d(this,"_totalFrames",0)}_render(e,i){let{width:s,height:o}=this;if(this.image instanceof HTMLVideoElement){if(j(this.image.getVideoPlaybackQuality)&&!Tn){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?i&&this.useTexture(n=>{n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.image)}):(i&&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)}},zo=class extends bs{constructor(e,i){super(e,document.createElement("video"));this._videoTrack=i;d(this,"_mediaStream");this.name="videoTrackSource",this._mediaStream=new MediaStream([i]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var i,s;this._videoTrack!==e&&((i=this._mediaStream)==null||i.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 km=`
39
+ b=${s}:${t}\r
40
+ `),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===Ti?(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,Ne=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(Ne,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=ye(Le());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||!Ri())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})}})}},Li=pc;d(Li,"EVENT_NETWORK_QUALITY","0");var Ht=new WeakMap;function Er({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:Ae,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&Yi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Qi)>=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=sr.getItem(this._storageKey);i&&(yield this.upload(i),sr.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&&sr.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,Pi);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>Pi&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Pi)}),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>Pi&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Pi)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Pi&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Pi)}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),sr.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=Ii(e,Ei.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([Er({settings:{timeout:500,retries:3}})],qo.prototype,"upload",1);var Pi=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}},Tr=_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 Tr,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 Tr,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 Tr,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 Tr;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&&fi(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?Xi.MAIN_OVERSEA:Xi.BACKUP_OVERSEA:e=i===h.MAIN?Xi.MAIN:Xi.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 tr(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 tr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var Uu=ye(Le(),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=`
41
41
  // \u9876\u70B9\u7740\u8272\u5668
42
42
  attribute vec4 a_position;
43
43
  attribute vec2 a_texCoord;
@@ -47,7 +47,7 @@ void main() {
47
47
  gl_Position = a_position;
48
48
  v_texCoord = a_texCoord;
49
49
  }
50
- `,xm=`
50
+ `,Lm=`
51
51
  // \u7247\u5143\u7740\u8272\u5668
52
52
  precision mediump float;
53
53
  varying vec2 v_texCoord;
@@ -55,6 +55,6 @@ uniform sampler2D u_texture;
55
55
 
56
56
  void main() {
57
57
  gl_FragColor = texture2D(u_texture, v_texCoord);
58
- } `,Pi=class extends P{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 i=this._canvas.getContext("webgl",{alpha:e.alpha});if(i){this._gl=i;try{let s=this.createShader(i.VERTEX_SHADER,km),o=this.createShader(i.FRAGMENT_SHADER,xm);this.defaultProgam=this.createProgram(s,o),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.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 zo(this,e)}createVideoTrackDestination(e){return new ys(this,e)}createVideoImageSource(e){return new bs(this,e)}set width(e){var i;(i=this._gl)==null||i.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 i;(i=this._gl)==null||i.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,i){var s;(s=this._gl)==null||s.viewport(0,0,e,i),this._canvas&&(this._canvas.width=e,this._canvas.height=i)}disconnect(){this.emit("disconnect")}destroy(e,i){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,i]}createShader(e,i){let s=this._gl,o=s.createShader(e);return s.shaderSource(o,i),s.compileShader(o),o}createProgram(e,i){let s=this._gl,o=s.createProgram();return s.attachShader(o,e),s.attachShader(o,i),s.linkProgram(o),o}useTexture(e,i,s){let o=this._gl;o.activeTexture(o.TEXTURE0+(s||0)),o.bindTexture(o.TEXTURE_2D,e),i(o),o.bindTexture(o.TEXTURE_2D,null)}};y([Z(P.INIT,"created")],Pi.prototype,"create",1),y([Z("created",P.INIT,{ignoreError:!0,success(r){r[0]&&(this.glFaild=!0,this.emit("unavailable",...r)),this.removeAllListeners()}})],Pi.prototype,"destroy",1);var wm=[1,0,1,1,0,0,0,1],Zo=class extends Be{constructor(t){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),t._gl)try{this.setTexBuffer(wm)}catch(e){t.destroy("mirror set texCoords faild",e)}else this.ctx2d&&setTimeout(e=>{e.scale(-1,1),e.translate(-this.width,0)},0,this.ctx2d)}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(()=>{this.useInputTexture(i=>{this.setAttributes({a_position:this.positionBuffer,a_texCoord:this.texCoordBuffer}),i.drawArrays(i.TRIANGLE_STRIP,0,4)})}),!0):!1}};var gc=class{constructor(t,e){this.node=t;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}},en=class extends Be{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0});d(this,"inputs",[])}addInput(e,i){if(this.inputs[i.zIndex])throw new Error("input already exists");let s=new gc(e,i);this.inputs[i.zIndex]=s}resize(e,i){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,...i){return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(i=>(i==null?void 0:i.node)===e)]=void 0}render(e){let i=this.context._gl;return!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&i?(this.useProgram(),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT|i.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:i,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:i,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 i;if(e&&((i=e.node)==null||i.disconnect(),e.positionBuffer&&this.context._gl))try{this.context._gl.deleteBuffer(e.positionBuffer)}catch(s){}})}};var tn=class extends Vu.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",(i,s)=>{this.emit("error",{reason:i,error:s}),this._log.warn("video context unavailable",i,s,`glFaild:${this.videoContext.glFaild}`),E.emit("262",{room:this._room,apiName:"videoCtxGl",error:s||new Error(i)}),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 i=e==="2d";this._use2d!==i&&(this._use2d=i,this.videoContext&&(this.clear(),this.videoContext.destroy(),this.videoContext.create({alpha:this._hasWaterMark,use2d:this._use2d}),this.update()))}enablePrintDetail(e=2e3){this._checkId=ee.run(jr,()=>{this.destination&&this._log.debug(this.destination.getInfo())},{delay:e})}destroy(){this.videoContext.destroy(),this.smallVideoContext.destroy(),ee.clearTask(this._checkId)}get active(){return(Vr&&Sn||this._isMixScreen||this._isMirror||this._hasWaterMark)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",i){E.emit("262",{room:this._room,apiName:e,error:i})}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 i=this.cameraTrack,{small:s,settings:o}=i;return s&&(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1,use2d:!0}),this.smallDestination=new qo(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)))),i.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 Zo(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 en(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,i){if(this._log.info("change input"),e instanceof xe)return this.setScreenTrack(e);if(e instanceof Le)return this.setCameraTrack(e);if(e instanceof ft)return e.setOutputMediaStreamTrack(e.mediaTrack)}removeInput(e){var i;e instanceof xe?((i=this.screenNode)==null||i.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Le?(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((i,s)=>{let o=new Image;o.crossOrigin="anonymous",o.src=e,o.onload=()=>i(o),o.onerror=s})}setWatermark(e){return p(this,null,function*(){let i=yield this.loadImage(e.imageUrl),{x:s=0,y:o=0,width:n=i.width,height:a=i.height}=e;this._hasWaterMark=!0,this._waterMarkOption={x:s,y:o,width:n,height:a,image:i},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 i;this._isMixScreen=e,this._isMixScreen||((i=this.screenNode)==null||i.close(),delete this.screenNode),this.update()}set mirror(e){var i;this._isMirror=e,this._isMirror||((i=this.mirrorNode)==null||i.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 Vm=0;var rn=class extends P{constructor(e){super("room");this.seq=++Vm;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,ie(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ie(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ie(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new Mu({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Pu({room:this}),this.badCaseDetector=new ku({room:this}),this.audioManager=new Co({room:this}),this.videoManager=new tn({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(He(e)){let{websocketProxy:i,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=i,this.proxy_wt=s,this.proxy_unified=a,a?(Ic([a,a]),_i(`https://${a}`)):(o&&_i(o),n&&Ic(n))}}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(i=>{e[i.userId]=i.remoteAudioTrack.stat}),e})}getTransportStats(){return p(this,null,function*(){var i;let e={rtt:((i=this.quality)==null?void 0:i.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 i={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;i[s.userId]=o.stat}),i})}checkDestroy(){if(this._isDestroyed)throw new C({code:I.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:I.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,i,s){return p(this,null,function*(){var n,a;let o=$();try{let{isCached:c,result:u,detailCost:l}=yield wu({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:s,userSig:this.userSig,frameWorkType:i});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)&&Mn(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,It=new WeakMap;function Os(){return function(r,t,e){let i=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:i,args:o,context:this,resolve:a,reject:c}),l===0&&s({fn:i,args:o,context:this,resolve:a,reject:c})}else di.set(this,[{fn:i,args:o,context:this,resolve:a,reject:c}]),s({fn:i,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 Uu(r){return function(t,e,i){let s=i.value;return i.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:I.API_CALL_ABORTED,message:r})),!1):!0});di.set(this,a)}return s.apply(this,o)},i}}function Bu(r){return function(t,e,i){let s=i.value;return i.value=function(...o){var a,c;let n=[];return(a=di.get(this))==null||a.forEach(u=>n.push(u)),(c=It.get(this))==null||c.forEach(u=>u.forEach(l=>n.push(l))),n.forEach(u=>{u.reject(new C({code:I.API_CALL_ABORTED,message:r}))}),di.delete(this),It.delete(this),s.apply(this,o)},i}}function Ac(r){return function(t,e,i){let s=i.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(It.has(u)&&It.get(u).has(o(c))){let f=It.get(u).get(o(c));f&&(f.shift(),f[0]&&n(N({},f[0])))}})};return i.value=function(...a){return new Promise((c,u)=>{if(It.has(this))if(It.get(this).has(o(a))){let l=It.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 It.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}]),It.set(this,l),n({fn:s,args:a,context:this,resolve:c,reject:u})}})},i}}var Ku=Ne(Me());var Rc=Ne(cc()),$u=r=>{let t=ue(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((i,s)=>{var o;if(i.ssrcs&&!T(i.ssrcs[0].id)){let n=Number(i.ssrcs[0].id),a=Number((o=i.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,t)=>{var a,c;let e=ue(r),i={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};i.ice.ufrag=String(e.media[0].iceUfrag),i.ice.password=e.media[0].icePwd||"",e.fingerprint&&(i.dtls.hash=e.fingerprint.type,i.dtls.fingerprint=e.fingerprint.hash,i.dtls.setup=e.setup||""),e.media[0].fingerprint&&(i.dtls.hash=e.media[0].fingerprint.type,i.dtls.fingerprint=e.media[0].fingerprint.hash),i.dtls.setup=e.media[0].setup||"";let s=e.media[0],o=e.media[1];s.ext&&(i.audio.extensions=s.ext.map(u=>({id:u.value,uri:u.uri}))),o.ext&&(i.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)}}),i.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];i.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 i},Fu=({serverAbility:r,clientAbility:t,offerSDP:e,enableCustomMessage:i})=>{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(Cc({mid:a,serverAbility:r,clientAbility:t,parsedOffer:s}))}),i&&o.media.push(s.media.find(a=>a.mid==="dc")),We(o)},Cc=({mid:r,serverAbility:t,clientAbility:e,parsedOffer:i,useAllCodec:s=!1})=>{let o={candidates:t.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:t.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:String(r),payloads:"",port:i.media[0].port,protocol:i.media[0].protocol,type:h.VIDEO,setup:t.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(t.video.codecs.length>0)if(s)for(let n=0;n<t.video.codecs.length;n++)sn(o,t.video.codecs[n]);else{let n=t.video.codecs.findIndex(a=>a.codec.toLowerCase()===(t.useVp8?"vp8":"h264"));sn(o,t.video.codecs[n])}else if(s)for(let n=0;n<e.video.codecs.length;n++)sn(o,e.video.codecs[n]);else sn(o,e.video.codecs[0]);return o.payloads=o.payloads.trim(),o},sn=(r,t)=>{r.payloads=`${r.payloads} ${t.payload}`,r.fmtp.push({payload:t.payload,config:t.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map(e=>({payload:t.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(r.payloads=`${r.payloads} ${t.rtx}`,r.fmtp.push({payload:t.rtx,config:`apt=${t.payload}`}),r.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};function Um(r){let t=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=>!t.has(e.uri)))}function Bm(r){if(!r.rtcpFb)return;let t=[];r.rtcpFb.forEach((e,i)=>{var s;t.push(e),r.rtcpFb&&((s=r.rtcpFb[i+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&t.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=t}function $m(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(t=>{t.config.includes("apt")||(t.config+=";sps-pps-idr-in-keyframe=1")})}function Hm(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}var Gu=r=>{let t=Rc.default.parse(r);return t.media.forEach(e=>{var i;(e.type===h.AUDIO||e.type===h.VIDEO)&&(Bm(e),$m(e),Hm(e),Um(e)),((i=e.payloads)==null?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")}),Rc.default.write(t)};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,ju=!1,Fm=new Set,Gm=r=>Ju>2&&!ju&&Fm.size===0&&r,Wm=1,Er=class extends Ku.default{constructor({signalChannel:e,room:i,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=i,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${Wm++}`,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(i=>i.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?$u(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 i=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${i}`),i==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():i==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=i=>this.emit("track",i),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=i=>{let s=new yc(i.data);this.emit("data_channel_msg",{data:s})},this._datachannel.onerror=i=>{this._log.warn("datachannel error",i)}),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:i}=this;!i||(this._log.debug(`dtls state: ${i.state}`),i.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():i.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,i=!1){return p(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let s=$(),o={type:"answer",sdp:Fu({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),i||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===I.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(),i=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:B.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});yield this.connect(i.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 i=Fe(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${i/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},i)}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 i=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${i} 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!rr()||this._peerConnection.getSenders().length===0?Qe:(e=this._peerConnection.getSenders()[0].transport,!gi()||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[i,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,i)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=i;let s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),i(new C({code:I.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:I.API_CALL_TIMEOUT,message:"connection timeout"});Ju+=1,Gm(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),ju=!0,this.emit(St.FIREWALL_RESTRICTION)),i(c)},Wr);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,i)=>{this.once("spc-reconnected",e),this.once("error",i)}):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(i){this._log.info(`addDownlink(${e.userId}) failed`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:i,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${i} ${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=Cc({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,i){return p(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${i}) 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(${i}) done`)})}getDownlinkMids(e){return this._downlinkMIDMap.get(e)}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:i,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&&i?l=i: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,i){let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),i==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=i*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:i,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=Q?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:Q?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:Q?e*1e3:e}]),i&&(n.media[1].bandwidth=[{type:a,limit:Q?i*1e3:i}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:Q?i*1e3:i}]),s&&(n.media[2].bandwidth=[{type:a,limit:Q?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:Q?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:Q?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:Q?o*1e3:o}]);let c={type:"offer",sdp:We(n)};return this.updateSDP({localDescription:c})}updateSDP({isNeedToCreateOffer:e=!1,localDescription:i,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"),i=yield this._peerConnection.createOffer()),i&&(yield this.setOffer(i)),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:g,stopped:b})=>({mid:m,currentDirection:f,direction:g,stopped:b})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._log.warn(`local sdp: ${i==null?void 0:i.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:Gu(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 i;(i=this._datachannel)==null||i.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()],Er.prototype,"updateSDP",1);var Nc=class{constructor(t){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(t);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(t).slice(4,2+2+this.len).buffer}},yc=class{constructor(t){d(this,"tinyId");d(this,"data");let e=new DataView(t),i=0,s=[];for(;i<e.byteLength;){let o=e.getUint16(i+2),n=new Nc(new Uint8Array(t).slice(i,i+2+2+o).buffer);s.push(n),i+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Wu=new Set;function ki(){let r=Math.floor(Math.random()*4294967296);return Wu.has(r)?ki():(Wu.add(r),r)}var Yu=Ne(Me());var xi=class extends Yu.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 Wo(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,i;return!!((i=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&i.sdp.includes("H264"))}};var bc=class extends xi{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:i,bigVideoRtxSsrc:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:i||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 i,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=!!((i=a[0])!=null&&i.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,i){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(i?i.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:i,isAuxiliary:s}){var a,c,u,l,m,f;if(!this.singlePC)return;if(yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),i){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new C({code:I.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264ENCODE})});Pe&&at()===115&&i.profile.width*i.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),i.setProfile(yt["480p_2"]),yield i.applyProfile()),this._publishingLocalVideoTrack=i}this._isPublishingAux=s;let n;i&&!s&&i.small&&(n=this._room.videoManager.smallTrack),et()&&(yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:i,smallTrack:n,isAuxiliary:s})),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(i&&(this.localAuxVideoTrack=i),e&&(this.localAuxAudioTrack=e)):(i&&(this.localMainVideoTrack=i),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,i),this.sendMutedFlag()})}publishByTransceiver({localAudioTrack:e,localVideoTrack:i,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let n=i==null?void 0:i.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(i=>{i&&(i==null||i.on("mute",this.sendMutedFlag,this),i==null||i.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(i=>{i&&(i==null||i.off("mute",this.sendMutedFlag,this),i==null||i.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:i}){let o=i&&i===this.localAuxVideoTrack,n=i==null?void 0:i.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,i),i==null||i.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let i={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:i,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(i=>{if(i.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw i})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:i}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":i&&(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 i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${i?h.AUXILIARY:h.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),mt()&&(yield this.addTrackByTransceiver(e,i))})}addTrackByTransceiver(e,i){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=i?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 i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${i?h.AUXILIARY:h.MAIN} stream`),mt()&&(yield this.removeTrackByTransceiver(e,i))})}removeTrackByTransceiver(e,i){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=i?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,i){return p(this,null,function*(){if(!Q)return;let s=!1,o=!1;this._log.info(`setting transceiver ${i.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(i.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
59
- `).map(u=>{if(u.match(new RegExp(`a=(${K.INACTIVE}|${K.RECVONLY}|${K.SENDONLY})`))&&a++,i.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
60
- `);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return p(this,null,function*(){var n;let i=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.mediaTrack;if(!i||i.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&&i[0]&&(yield i[0].replaceTrack(this._audioManager.mixedAudioTrack)),s.kind===h.VIDEO&&(!o&&i[1]&&(yield i[1].replaceTrack(e.outMediaTrack||s)),o&&i[3]&&(yield i[3].replaceTrack(e.outMediaTrack)))})}setBandwidth(o){return p(this,arguments,function*({bandwidth:e,type:i,videoType:s}){if(this.singlePC){let n={};i===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 i=this._peerConnection.getSenders();if(e===h.AUXILIARY&&i[3]&&i[3].track)return i[3].track.id;if(e===h.VIDEO&&i[1]&&i[1].track)return i[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let i=this.localMainVideoTrack.mediaTrack;if(i)return i.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let i=this.localAuxVideoTrack.mediaTrack;if(i)return i.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,i){if(e!==0)throw e===Ei?(this._log.error(me.NOT_SUPPORTED_H264ENCODE),new C({code:I.NOT_SUPPORTED_H264,message:D({key:O.NOT_SUPPORTED_H264ENCODE})})):new C({code:I.UNKNOWN,message:D({key:O.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.PUBLISH_RESULT,code:e,message:i}})})}sendSEI(e,i){var s;(s=this._sei)==null||s.push(e,i)}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}))})}},Oc=bc;function Xu(r){return Object.keys(r).filter(t=>r[t])}var on=class extends xi{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 ar(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 Xt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var i,s,o;e!==this._flag&&(this._flag=e,(i=this.remoteAudioTrack)==null||i.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 i=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&i!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:i,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:i,state:e})),s}onTrack(e){let i=e.streams[0],{track:s}=e;if(i.id.split("-")[0]!==this.tinyId)return;let a=i.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,i){return p(this,null,function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info(`subscribe ${i} ${Xu(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(i)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new C({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:i}){var a;if(i==="main"&&!this.isMainStreamSubscribed||i==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${i} 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"} ${i} [${Xu(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,i=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:i.audio,bigVideo:i.video,auxVideo:i.auxiliary,smallVideo:i.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:i}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=i}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,i=!0){if(!!this.singlePC){if(this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected(),i||!this.hasSSRC){let s={audioSsrc:ki(),bigVideoSsrc:ki(),bigVideoRtxSsrc:ki(),auxVideoSsrc:ki(),auxVideoRtxSsrc:ki()},{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(...t){return new Promise((e,i)=>{let s=o=>{this.off("closed",s),i(new C({code:I.API_CALL_ABORTED,message:D({key:O.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,t).then(e,i).finally(()=>{this.off("closed",s)})})})],on.prototype,"subscribe",1);var Qu=on;function qu(){return G(r=>function(...t){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(i=>i.outMediaTrack&&i.state==="capture"),!t.length))return;E.emit("61",{room:this}),t.forEach(i=>{i.kind==="audio"&&this.audioManager.addAudioTrack(i)});let e=r.apply(this,t);return t.forEach(i=>{var s;i.publish(this,e),i.kind==="audio"&&((s=this.audioManager.localMixAudioTrack)==null||s.publish(this,e))}),e})})}function zu(){return G(r=>function(...t){t.forEach(i=>{i.kind==="audio"&&this.audioManager.removeAudioTrack(i)});let e=r.apply(this,t);return t.forEach(i=>i.unpublish()),e})}var{isString:Zu,isPlainObject:lL,isUndefined:Tr,getNetworkType:Km,getTerminalType:Jm,isEmpty:Ds}=ge,gt=class extends rn{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=Km();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 Po(this.userId,this._log),this._version=Se,this.sdpSemantics=Yi,Tr(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=Tr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!Tr(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,i,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=Mc(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,i=!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)}),ie((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 Er({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:Jm(),netType:Jt[this._networkType],bussinessInfo:this._businessInfo,ability:n};i&&(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:I.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:g,message:b,data:L}=f.data;E.emit(_.JOIN_RECEIVED_CMD_RES,{room:this,code:g}),g===0?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=L.publishers,this.singlePC&&this.singlePC.connect(L.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${g} error: ${b}`),o(new C({code:I.JOIN_ROOM_FAILED,extraCode:g,message:D({key:O.JOIN_ROOM_FAILED,data:{error:b,code:g}})})))})}))}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"),X.logSuccessEvent({userId:this.userId,eventType:be.REJOIN}),this.singlePC){let e=i=>{var s;i.state==="CONNECTED"&&((s=this.singlePC)==null||s.off(St.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof Oc&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(o=>{o.installEvents(),o.doSubscribe()}))};this.singlePC.on(St.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof jo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),X.logFailedEvent({userId:this.userId,eventType:be.REJOIN,error:e}),this.emit("error",new C({code:I.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:i}=this.getSignalChannelUrl(),s=this._signalChannel||Eu(this.userId),o=!!(s&&s.isConnected&&s.keepAlive);return this._log.info(`setup signal channel. reuse: ${+o}`),o?(s.url=e,s.backupUrl=i,s.room=this,this._signalChannel=s):this._signalChannel=new Ts({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:i,room:this}),this._networkQuality||(this._networkQuality=new Li({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Li.EVENT_NETWORK_QUALITY,n=>{this.emit("network-quality",n)})),Ee(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(X.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(i){}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=ee.run(dt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),ee.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),i=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},i);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 i=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:i}),this.userManager.setRemotePublishedUserList(i)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(i=>i.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:i,flag:s}){let o=new(this.singlePC?Qu:uc)({userId:e,tinyId:i,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,i="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(i),this.emit("remote-unpublished",s))}installDownlinkEvents(e,i){e.on("sei-message",s=>{this.emit("sei-message",s)}),e.on("error",s=>{let o=s.getCode();o!==I.ICE_TRANSPORT_ERROR&&(o===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(i),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=ee.run(dt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){ee.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:i})=>{let{code:s,message:o}=i;if(s===0)return(i.data&&i.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||!oc)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let i=0;i<e.length;i++)if(e[i].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){this.singlePC||this.getAllConnections().forEach(i=>{if(i instanceof Ue&&!i.getIsReconnecting()){let s=i.getPeerConnection();s&&s.connectionState===te.CLOSED&&(this._log.warn(`[${i.getUserId()}] pc is closed but not reconnect`),i.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),X.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 i=this.uplinkConnection;this.uplinkConnection=new jo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),i.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:i.localMainAudioTrack,localVideoTrack:i.localMainVideoTrack,isAuxiliary:!1})),i.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:i.localAuxAudioTrack,localVideoTrack:i.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach(i=>{let s=new uc({userId:i.userId,tinyId:i.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:i.flag,remoteAudioTrack:i.remoteAudioTrack,remoteVideoTrack:i.remoteVideoTrack,remoteAuxiliaryTrack:i.remoteAuxiliaryTrack});this.installDownlinkEvents(s,i.userId),this.remotePublishedUserMap.set(i.userId,s),i.isMainStreamSubscribed&&s.subscribe(i.subscribeState,"main"),i.isAuxStreamSubscribed&&s.subscribe(i.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:I.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 i={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(i.data)}`),this._signalChannel.sendWaitForResponseWithRetry(i).then(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new C({code:I.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()===I.API_CALL_TIMEOUT&&(s=new C({code:I.SWITCH_ROLE_FAILED,message:D({key:O.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return p(this,null,function*(){let i={},s={};e.forEach(c=>{c instanceof ve&&(c instanceof xt?s.audio=c:i.audio=c),c instanceof Le&&(c instanceof xe&&c.mediaType===2?s.video=c:i.video=c)});let o=Ds(i),n=Ds(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Oc({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new jo({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!==I.ICE_TRANSPORT_ERROR&&(u===I.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:i.audio,localVideoTrack:i.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 i={},s={};e.forEach(o=>{!o.mediaTrack||(o instanceof ve&&(o instanceof xt?s.audio=o:i.audio=o),o instanceof Le&&(o instanceof xe&&o.mediaType===2?s.video=o:i.video=o))});try{let o=e.map(n=>n.kind).join(",");Ds(i)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.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 i=this.uplinkConnection.addTrack(e);return e.publish(this,i),i}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(i=>(e.unpublish(),i))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(i=>{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:i}=e[0],s=this.remotePublishedUserMap.get(i);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(i);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() => ${i} ${o} [${Jo(n)}] prev: [${Jo(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():I.UNKNOWN,c=n;throw n instanceof C?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new C({code:I.API_CALL_ABORTED,message:D({key:O.API_CALL_ABORTED,data:{message:n.message,userId:i,streamType:o}})}),this._log.warn(c)):(c=new C({code:a,message:D({key:O.SUBSCRIBE_FAILED,data:{message:n.message,userId:i,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:i}=e[0],s=this.remotePublishedUserMap.get(i);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${i} ${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,i){if(e<=0){this._enableAudioVolumeEvaluation=!1,ee.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(_.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&ee.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=ee.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:i})}getLocalAudioStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let i=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:i.audio.bytesSent,packetsSent:i.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:i,packetsSent:s,framesEncoded:o,framesSent:n,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:i,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 i=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=i.rtt}for(let[,i]of this.remotePublishedUserMap){let s=yield this._stats.getReceiverStats(i);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let i={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(i[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(i[s]=o.remoteAuxiliaryTrack.stat);return i})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[i,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[i]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,i){this._log.info(`set turn server: ${JSON.stringify(e)} ${i||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(ge.getTurnServer(o))):ge.isPlainObject(e)&&s.push(ge.getTurnServer(e)),this._turnServers=s,i&&(this._iceTransportPolicy=i)}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,i=!0){return this._signalChannel.sendWaitForResponse({command:i?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:i?B.START_PUBLISH_TENCENT_CDN_RES:B.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,i=!0){return this._signalChannel.sendWaitForResponse({command:i?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:i?B.STOP_PUBLISH_TENCENT_CDN_RES:B.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var i;(i=this._signalChannel)==null||i.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:""},i=ge.getEnv();return i?(e.mainUrl=`wss://${i}.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 i=e==null?void 0:e.muteState.hasSmall,s=e==null?void 0:e.muteState.hasVideo;if(!i&&!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&&i||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(i&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{c&&!u&&l>=1&&(n.isSubscribing=!0,n.reSubscribeCount=l-1,!i&&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 ${Qi-n.reSubscribeCount}.`),n.isSubscribing=!1,n.reSubscribeCount=Qi)}catch(f){this._log.info(`change [${o}] to ${m.smallVideo?"small":"big"} video failed. count ${Qi-n.reSubscribeCount}.`),n.isSubscribing=!1,l===0&&this._changeBigSmallRecords.delete(o)}})}changeType(e,i){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Qi};this._changeBigSmallRecords.set(i.userId,o),this._log.info(`set [${i.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let i={};if(Zu(e.businessInfo)&&(i=JSON.parse(e.businessInfo)),!Tr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new C({code:I.INVALID_PARAMETER,message:D({key:O.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,i.Str_uc_params||(i.Str_uc_params={}),i.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Tr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new C({code:I.INVALID_PARAMETER,message:D({key:O.INVALID_USER_DEFINE_RECORDID})});i.Str_uc_params||(i.Str_uc_params={}),i.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Tr(e.userDefinePushArgs))if(Zu(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)i.Str_uc_params||(i.Str_uc_params={}),i.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new C({code:I.INVALID_PARAMETER,message:D({key:O.INVALID_USER_DEFINE_PUSH_ARGS})});Ds(i)||(this._businessInfo=JSON.stringify(i))}sendSEI(e,i){var s;(s=this.uplinkConnection)==null||s.sendSEI(e,i)}};y([Z(["left",P.INIT],"joined"),_r({settings:{retries:1,timeout:0},onError(r,t,e){this._isUsingCachedSchedule&&!this._isDestroyed?(this._log.warn("is using cached schedule, retry join"),ci(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(r),e(r))}}),hu()],gt.prototype,"join",1),y([Z("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),mu(),Bu("leave room"),Cs({fnName:"publish",validateArgs:!1}),Cs({fnName:"unsubscribe",validateArgs:!1})],gt.prototype,"leave",1),y([Os(),qu(),_r({settings:{retries:Ot,timeout:r=>Fe(r)},onError(r,t,e){var i;(i=r.message)!=null&&i.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${r}`),e(r),E.emit(_.PUBLISH_FAILED,{room:this}))}})],gt.prototype,"publish",1),y([Cs({fnName:"publish",callback(...r){var t;this.localTracks.size===0&&((t=this.uplinkConnection)==null||t.close("you unpublished"),this.uplinkConnection=null,r.forEach(e=>e.unpublish()))}}),Uu("api-call"),Os(),zu()],gt.prototype,"unpublish",1),y([Ac((...r)=>r[0].userId),pu(),_r({settings:{retries:Ot,timeout:r=>Fe(r)},onError(r,t,e,i){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${r}`),e(r),E.emit(_.SUBSCRIBE_FAILED,{room:this,remoteTracks:i}))}})],gt.prototype,"subscribe",1),y([Cs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(t=>{let e=this.remotePublishedUserMap.get(t.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Ac((...r)=>r[0].userId)],gt.prototype,"unsubscribe",1);Es.create=Es._create.bind(Es,gt);var EL=Es;export{EL as default};
58
+ } `,xi=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")],xi.prototype,"create",1),y([ee("created",L.INIT,{ignoreError:!0,success(r){r[0]&&(this.glFaild=!0,this.emit("unavailable",...r)),this.removeAllListeners()}})],xi.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 xi({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 xi({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(Si,()=>{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 Me)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 Me?(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]),fi(`https://${a}`)):(o&&fi(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)&&fi(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=ye(Le());var Cc=ye(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,gr=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!or()||this._peerConnection.getSenders().length===0?qe:(e=this._peerConnection.getSenders()[0].transport,!Ri()||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()],gr.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 wi(){let r=Math.floor(Math.random()*4294967296);return Ku.has(r)?wi():(Ku.add(r),r)}var Qu=ye(Le());var Vi=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 Vi{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})});Ie&&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
59
+ `).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
60
+ `);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===Ti?(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 Vi{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 dr(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:wi(),bigVideoSsrc:wi(),bigVideoRtxSsrc:wi(),auxVideoSsrc:wi(),auxVideoRtxSsrc:wi()},{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:lk,isUndefined:Sr,getNetworkType:Gm,getTerminalType:Wm,isEmpty:Ds}=Re,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=Ae,this.sdpSemantics=qi,Sr(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=Sr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!Sr(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 gr({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:Oe.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:Oe.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 Li({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Li.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:_i,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 ke&&(c instanceof xt?s.audio=c:t.audio=c),c instanceof Me&&(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 ke&&(o instanceof xt?s.audio=o:t.audio=o),o instanceof Me&&(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(Re.getTurnServer(o))):Re.isPlainObject(e)&&s.push(Re.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=Re.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 ${zi-n.reSubscribeCount}.`),n.isSubscribing=!1,n.reSubscribeCount=zi)}catch(f){this._log.info(`change [${o}] to ${m.smallVideo?"small":"big"} video failed. count ${zi-n.reSubscribeCount}.`),n.isSubscribing=!1,l===0&&this._changeBigSmallRecords.delete(o)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:zi};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)),!Sr(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(!Sr(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(!Sr(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"),Er({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(),Er({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(),Er({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 Ek=Es;export{Ek as default};