trtc-sdk-v5 5.6.0-beta.7 → 5.6.0-beta.8
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/core.d.ts +4 -14
- package/index.d.ts +1770 -1770
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +26 -96
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var th=Object.create;var $r=Object.defineProperty,ih=Object.defineProperties,pd=Object.getOwnPropertyDescriptor,rh=Object.getOwnPropertyDescriptors,sh=Object.getOwnPropertyNames,sn=Object.getOwnPropertySymbols,_d=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty,fd=Object.prototype.propertyIsEnumerable,nh=Reflect.get;var Hr=Math.pow,Bo=(r,i,e)=>i in r?$r(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,y=(r,i)=>{for(var e in i||(i={}))$o.call(i,e)&&Bo(r,e,i[e]);if(sn)for(var e of sn(i))fd.call(i,e)&&Bo(r,e,i[e]);return r},L=(r,i)=>ih(r,rh(i));var Ed=(r,i)=>{var e={};for(var t in r)$o.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&sn)for(var t of sn(r))i.indexOf(t)<0&&fd.call(r,t)&&(e[t]=r[t]);return e};var Pt=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),Fr=(r,i)=>{for(var e in i)$r(r,e,{get:i[e],enumerable:!0})},oh=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of sh(i))!$o.call(r,s)&&s!==e&&$r(r,s,{get:()=>i[s],enumerable:!(t=pd(i,s))||t.enumerable});return r};var ve=(r,i,e)=>(e=r!=null?th(_d(r)):{},oh(i||!r||!r.__esModule?$r(e,"default",{value:r,enumerable:!0}):e,r));var b=(r,i,e,t)=>{for(var s=t>1?void 0:t?pd(i,e):i,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(t?o(i,e,s):o(s))||s);return t&&s&&$r(i,e,s),s};var u=(r,i,e)=>(Bo(r,typeof i!="symbol"?i+"":i,e),e);var Re=(r,i,e)=>nh(_d(r),e,i);var p=(r,i,e)=>new Promise((t,s)=>{var n=c=>{try{a(e.next(c))}catch(d){s(d)}},o=c=>{try{a(e.throw(c))}catch(d){s(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(n,o);a((e=e.apply(r,i)).next())});var Ue=Pt((h_,Ho)=>{"use strict";var ah=Object.prototype.hasOwnProperty,Oe="~";function Gr(){}Object.create&&(Gr.prototype=Object.create(null),new Gr().__proto__||(Oe=!1));function ch(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function Td(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var n=new ch(e,t||r,s),o=Oe?Oe+i:i;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],n]:r._events[o].push(n):(r._events[o]=n,r._eventsCount++),r}function nn(r,i){--r._eventsCount===0?r._events=new Gr:delete r._events[i]}function Ce(){this._events=new Gr,this._eventsCount=0}Ce.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)ah.call(e,t)&&i.push(Oe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Ce.prototype.listeners=function(i){var e=Oe?Oe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,n=t.length,o=new Array(n);s<n;s++)o[s]=t[s].fn;return o};Ce.prototype.listenerCount=function(i){var e=Oe?Oe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Ce.prototype.emit=function(i,e,t,s,n,o){var a=Oe?Oe+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,l,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),d){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,n),!0;case 6:return c.fn.call(c.context,e,t,s,n,o),!0}for(m=1,l=new Array(d-1);m<d;m++)l[m-1]=arguments[m];c.fn.apply(c.context,l)}else{var _=c.length,T;for(m=0;m<_;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),d){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(T=1,l=new Array(d-1);T<d;T++)l[T-1]=arguments[T];c[m].fn.apply(c[m].context,l)}}return!0};Ce.prototype.on=function(i,e,t){return Td(this,i,e,t,!1)};Ce.prototype.once=function(i,e,t){return Td(this,i,e,t,!0)};Ce.prototype.removeListener=function(i,e,t,s){var n=Oe?Oe+i:i;if(!this._events[n])return this;if(!e)return nn(this,n),this;var o=this._events[n];if(o.fn)o.fn===e&&(!s||o.once)&&(!t||o.context===t)&&nn(this,n);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==e||s&&!o[a].once||t&&o[a].context!==t)&&c.push(o[a]);c.length?this._events[n]=c.length===1?c[0]:c:nn(this,n)}return this};Ce.prototype.removeAllListeners=function(i){var e;return i?(e=Oe?Oe+i:i,this._events[e]&&nn(this,e)):(this._events=new Gr,this._eventsCount=0),this};Ce.prototype.off=Ce.prototype.removeListener;Ce.prototype.addListener=Ce.prototype.on;Ce.prefixed=Oe;Ce.EventEmitter=Ce;typeof Ho!="undefined"&&(Ho.exports=Ce)});var Da=Pt((Vf,Yd)=>{var Qd=Yd.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:%s 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":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{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:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(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:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Qd).forEach(function(r){var i=Qd[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var eu=Pt(jt=>{var gr=function(r){return String(Number(r))===r?Number(r):r},fm=function(r,i,e,t){if(t&&!e)i[t]=gr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=gr(r[s+1]))},Em=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;fm(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},qd=Da(),Tm=RegExp.prototype.test.bind(/^([a-z])=(.*)/);jt.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(Tm).forEach(function(s){var n=s[0],o=s.slice(2);n==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(qd[n]||[]).length;a+=1){var c=qd[n][a];if(c.reg.test(o))return Em(c,t,o)}}),i.media=e,i};var Zd=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=gr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};jt.parseParams=function(r){return r.split(/;\s?/).reduce(Zd,{})};jt.parseFmtpConfig=jt.parseParams;jt.parsePayloads=function(r){return r.toString().split(" ").map(Number)};jt.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(gr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};jt.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Zd,{})})};jt.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=gr(e):(t=gr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var iu=Pt((Bf,tu)=>{var ka=Da(),gm=/%[sdv%]/g,Sm=function(r){var i=1,e=arguments,t=e.length;return r.replace(gm,function(s){if(i>=t)return s;var n=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Is=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 n=0;n<i.names.length;n+=1){var o=i.names[n];i.name?s.push(e[i.name][o]):s.push(e[i.names[n]])}else s.push(e[i.name]);return Sm.apply(null,s)},Im=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Am=["i","c","b","a"];tu.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=i.outerOrder||Im,t=i.innerOrder||Am,s=[];return e.forEach(function(n){ka[n].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Is(n,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(Is(n,o,a))})})}),r.media.forEach(function(n){s.push(Is("m",ka.m[0],n)),t.forEach(function(o){ka[o].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(Is(o,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(c){s.push(Is(o,a,c))})})})}),s.join(`\r
|
|
1
|
+
var Zl=Object.create;var Vr=Object.defineProperty,eh=Object.defineProperties,pd=Object.getOwnPropertyDescriptor,th=Object.getOwnPropertyDescriptors,ih=Object.getOwnPropertyNames,tn=Object.getOwnPropertySymbols,_d=Object.getPrototypeOf,Ho=Object.prototype.hasOwnProperty,fd=Object.prototype.propertyIsEnumerable,rh=Reflect.get;var Ur=Math.pow,$o=(r,i,e)=>i in r?Vr(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,N=(r,i)=>{for(var e in i||(i={}))Ho.call(i,e)&&$o(r,e,i[e]);if(tn)for(var e of tn(i))fd.call(i,e)&&$o(r,e,i[e]);return r},M=(r,i)=>eh(r,th(i));var Ed=(r,i)=>{var e={};for(var t in r)Ho.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&tn)for(var t of tn(r))i.indexOf(t)<0&&fd.call(r,t)&&(e[t]=r[t]);return e};var Lt=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),Br=(r,i)=>{for(var e in i)Vr(r,e,{get:i[e],enumerable:!0})},sh=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of ih(i))!Ho.call(r,s)&&s!==e&&Vr(r,s,{get:()=>i[s],enumerable:!(t=pd(i,s))||t.enumerable});return r};var ve=(r,i,e)=>(e=r!=null?Zl(_d(r)):{},sh(i||!r||!r.__esModule?Vr(e,"default",{value:r,enumerable:!0}):e,r));var b=(r,i,e,t)=>{for(var s=t>1?void 0:t?pd(i,e):i,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(t?o(i,e,s):o(s))||s);return t&&s&&Vr(i,e,s),s};var u=(r,i,e)=>($o(r,typeof i!="symbol"?i+"":i,e),e);var Ae=(r,i,e)=>rh(_d(r),e,i);var p=(r,i,e)=>new Promise((t,s)=>{var n=c=>{try{a(e.next(c))}catch(d){s(d)}},o=c=>{try{a(e.throw(c))}catch(d){s(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(n,o);a((e=e.apply(r,i)).next())});var Ve=Lt((a_,Fo)=>{"use strict";var nh=Object.prototype.hasOwnProperty,Oe="~";function $r(){}Object.create&&($r.prototype=Object.create(null),new $r().__proto__||(Oe=!1));function oh(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function gd(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var n=new oh(e,t||r,s),o=Oe?Oe+i:i;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],n]:r._events[o].push(n):(r._events[o]=n,r._eventsCount++),r}function rn(r,i){--r._eventsCount===0?r._events=new $r:delete r._events[i]}function Re(){this._events=new $r,this._eventsCount=0}Re.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)nh.call(e,t)&&i.push(Oe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Re.prototype.listeners=function(i){var e=Oe?Oe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,n=t.length,o=new Array(n);s<n;s++)o[s]=t[s].fn;return o};Re.prototype.listenerCount=function(i){var e=Oe?Oe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Re.prototype.emit=function(i,e,t,s,n,o){var a=Oe?Oe+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,l,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),d){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,n),!0;case 6:return c.fn.call(c.context,e,t,s,n,o),!0}for(m=1,l=new Array(d-1);m<d;m++)l[m-1]=arguments[m];c.fn.apply(c.context,l)}else{var _=c.length,g;for(m=0;m<_;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),d){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(g=1,l=new Array(d-1);g<d;g++)l[g-1]=arguments[g];c[m].fn.apply(c[m].context,l)}}return!0};Re.prototype.on=function(i,e,t){return gd(this,i,e,t,!1)};Re.prototype.once=function(i,e,t){return gd(this,i,e,t,!0)};Re.prototype.removeListener=function(i,e,t,s){var n=Oe?Oe+i:i;if(!this._events[n])return this;if(!e)return rn(this,n),this;var o=this._events[n];if(o.fn)o.fn===e&&(!s||o.once)&&(!t||o.context===t)&&rn(this,n);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==e||s&&!o[a].once||t&&o[a].context!==t)&&c.push(o[a]);c.length?this._events[n]=c.length===1?c[0]:c:rn(this,n)}return this};Re.prototype.removeAllListeners=function(i){var e;return i?(e=Oe?Oe+i:i,this._events[e]&&rn(this,e)):(this._events=new $r,this._eventsCount=0),this};Re.prototype.off=Re.prototype.removeListener;Re.prototype.addListener=Re.prototype.on;Re.prefixed=Oe;Re.EventEmitter=Re;typeof Fo!="undefined"&&(Fo.exports=Re)});var Da=Lt((Of,Xd)=>{var Kd=Xd.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:%s 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":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{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:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(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:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Kd).forEach(function(r){var i=Kd[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var qd=Lt(Gt=>{var _r=function(r){return String(Number(r))===r?Number(r):r},lm=function(r,i,e,t){if(t&&!e)i[t]=_r(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=_r(r[s+1]))},hm=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;lm(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Qd=Da(),mm=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Gt.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(mm).forEach(function(s){var n=s[0],o=s.slice(2);n==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Qd[n]||[]).length;a+=1){var c=Qd[n][a];if(c.reg.test(o))return hm(c,t,o)}}),i.media=e,i};var zd=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=_r(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};Gt.parseParams=function(r){return r.split(/;\s?/).reduce(zd,{})};Gt.parseFmtpConfig=Gt.parseParams;Gt.parsePayloads=function(r){return r.toString().split(" ").map(Number)};Gt.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(_r),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Gt.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(zd,{})})};Gt.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=_r(e):(t=_r(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Zd=Lt((kf,Yd)=>{var ka=Da(),pm=/%[sdv%]/g,_m=function(r){var i=1,e=arguments,t=e.length;return r.replace(pm,function(s){if(i>=t)return s;var n=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},gs=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 n=0;n<i.names.length;n+=1){var o=i.names[n];i.name?s.push(e[i.name][o]):s.push(e[i.names[n]])}else s.push(e[i.name]);return _m.apply(null,s)},fm=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Em=["i","c","b","a"];Yd.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=i.outerOrder||fm,t=i.innerOrder||Em,s=[];return e.forEach(function(n){ka[n].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(gs(n,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(gs(n,o,a))})})}),r.media.forEach(function(n){s.push(gs("m",ka.m[0],n)),t.forEach(function(o){ka[o].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(gs(o,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(c){s.push(gs(o,a,c))})})})}),s.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var ru=Pt(Kt=>{var Pi=eu(),Rm=iu();Kt.write=Rm;Kt.parse=Pi.parse;Kt.parseParams=Pi.parseParams;Kt.parseFmtpConfig=Pi.parseFmtpConfig;Kt.parsePayloads=Pi.parsePayloads;Kt.parseRemoteCandidates=Pi.parseRemoteCandidates;Kt.parseImageAttributes=Pi.parseImageAttributes;Kt.parseSimulcastStreamList=Pi.parseSimulcastStreamList});var zc=Pt((Wb,Il)=>{var Sl=Il.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:%s 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":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{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:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(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:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Sl).forEach(function(r){var i=Sl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Cl=Pt(si=>{var Pr=function(r){return String(Number(r))===r?Number(r):r},xp=function(r,i,e,t){if(t&&!e)i[t]=Pr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Pr(r[s+1]))},Pp=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;xp(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Al=zc(),wp=RegExp.prototype.test.bind(/^([a-z])=(.*)/);si.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(wp).forEach(function(s){var n=s[0],o=s.slice(2);n==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Al[n]||[]).length;a+=1){var c=Al[n][a];if(c.reg.test(o))return Pp(c,t,o)}}),i.media=e,i};var Rl=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Pr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};si.parseParams=function(r){return r.split(/;\s?/).reduce(Rl,{})};si.parseFmtpConfig=si.parseParams;si.parsePayloads=function(r){return r.toString().split(" ").map(Number)};si.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Pr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};si.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Rl,{})})};si.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Pr(e):(t=Pr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Nl=Pt((jb,yl)=>{var Qc=zc(),Vp=/%[sdv%]/g,Up=function(r){var i=1,e=arguments,t=e.length;return r.replace(Vp,function(s){if(i>=t)return s;var n=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},js=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 n=0;n<i.names.length;n+=1){var o=i.names[n];i.name?s.push(e[i.name][o]):s.push(e[i.names[n]])}else s.push(e[i.name]);return Up.apply(null,s)},Bp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],$p=["i","c","b","a"];yl.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=i.outerOrder||Bp,t=i.innerOrder||$p,s=[];return e.forEach(function(n){Qc[n].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(js(n,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(js(n,o,a))})})}),r.media.forEach(function(n){s.push(js("m",Qc.m[0],n)),t.forEach(function(o){Qc[o].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(js(o,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(c){s.push(js(o,a,c))})})})}),s.join(`\r
|
|
3
|
+
`}});var eu=Lt(Wt=>{var Li=qd(),gm=Zd();Wt.write=gm;Wt.parse=Li.parse;Wt.parseParams=Li.parseParams;Wt.parseFmtpConfig=Li.parseFmtpConfig;Wt.parsePayloads=Li.parsePayloads;Wt.parseRemoteCandidates=Li.parseRemoteCandidates;Wt.parseImageAttributes=Li.parseImageAttributes;Wt.parseSimulcastStreamList=Li.parseSimulcastStreamList});var Qc=Lt((Bb,Tl)=>{var gl=Tl.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:%s 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":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{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:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(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:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(gl).forEach(function(r){var i=gl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Al=Lt(ii=>{var Mr=function(r){return String(Number(r))===r?Number(r):r},Dp=function(r,i,e,t){if(t&&!e)i[t]=Mr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Mr(r[s+1]))},kp=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;Dp(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Sl=Qc(),Mp=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ii.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(Mp).forEach(function(s){var n=s[0],o=s.slice(2);n==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Sl[n]||[]).length;a+=1){var c=Sl[n][a];if(c.reg.test(o))return kp(c,t,o)}}),i.media=e,i};var Il=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Mr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};ii.parseParams=function(r){return r.split(/;\s?/).reduce(Il,{})};ii.parseFmtpConfig=ii.parseParams;ii.parsePayloads=function(r){return r.toString().split(" ").map(Number)};ii.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Mr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};ii.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Il,{})})};ii.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Mr(e):(t=Mr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Cl=Lt((Hb,Rl)=>{var zc=Qc(),Lp=/%[sdv%]/g,xp=function(r){var i=1,e=arguments,t=e.length;return r.replace(Lp,function(s){if(i>=t)return s;var n=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Ws=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 n=0;n<i.names.length;n+=1){var o=i.names[n];i.name?s.push(e[i.name][o]):s.push(e[i.names[n]])}else s.push(e[i.name]);return xp.apply(null,s)},Pp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],wp=["i","c","b","a"];Rl.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=i.outerOrder||Pp,t=i.innerOrder||wp,s=[];return e.forEach(function(n){zc[n].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Ws(n,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(Ws(n,o,a))})})}),r.media.forEach(function(n){s.push(Ws("m",zc.m[0],n)),t.forEach(function(o){zc[o].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(Ws(o,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(c){s.push(Ws(o,a,c))})})})}),s.join(`\r
|
|
4
4
|
`)+`\r
|
|
5
|
-
`}});var Yc=Pt(ni=>{var Ki=Cl(),Hp=Nl();ni.write=Hp;ni.parse=Ki.parse;ni.parseParams=Ki.parseParams;ni.parseFmtpConfig=Ki.parseFmtpConfig;ni.parsePayloads=Ki.parsePayloads;ni.parseRemoteCandidates=Ki.parseRemoteCandidates;ni.parseImageAttributes=Ki.parseImageAttributes;ni.parseSimulcastStreamList=Ki.parseSimulcastStreamList});import KL from"webrtc-adapter";var ul=ve(Ue());var gd=(D=>(D[D.INVALID_PARAMETER=4096]="INVALID_PARAMETER",D[D.INVALID_OPERATION=4097]="INVALID_OPERATION",D[D.NOT_SUPPORTED=4098]="NOT_SUPPORTED",D[D.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",D[D.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",D[D.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",D[D.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",D[D.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",D[D.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",D[D.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",D[D.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",D[D.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",D[D.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",D[D.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",D[D.CLIENT_BANNED=16448]="CLIENT_BANNED",D[D.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",D[D.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",D[D.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",D[D.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",D[D.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",D[D.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",D[D.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",D[D.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",D[D.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",D[D.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",D[D.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",D[D.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",D[D.API_CALL_ABORTED=16461]="API_CALL_ABORTED",D[D.UNKNOWN=65535]="UNKNOWN",D))(gd||{}),S=gd;var dh=function(r){for(let i in S)if(S[i]===r)return i;return"UNKNOWN"},Fo=class extends Error{constructor({name:e="RtcError",message:t,code:s=S.UNKNOWN,extraCode:n=0,constraint:o}){let a=`<${dh(s)} 0x${s.toString(16)}>`,c=`${t}${o?` constraint: ${o}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=s,this.extraCode=n,this.name=e,this.message=c,this.constraint=o,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},N=Fo;var Sd=new Date().getTime(),Go=0,Id=function(r){Sd=r,Go=Sd-new Date().getTime();let i=new Date;i.setTime(r),A.info(`baseTime from server: ${i} offset: ${Go}`)},Wr=function(){return new Date().getTime()+Go},on=function(){let r=new Date;return r.setTime(Wr()),r.toLocaleString()};var De={};Fr(De,{bytes2ms:()=>qh,convertObjectNumberToInt:()=>wn,copyProperties:()=>Yh,deepClone:()=>fr,deepMerge:()=>Wt,env:()=>ci,fibonacci:()=>_r,formatedTime:()=>cm,getAbilityConfigUrl:()=>Ud,getConstructorName:()=>xn,getContainerFromElement:()=>om,getEnv:()=>zh,getInternalVersion:()=>im,getLoggerUrl:()=>pi,getMuteStateFromFlag:()=>Ei,getNetworkQuality:()=>sm,getNetworkType:()=>Ia,getNumNetworkType:()=>Er,getOSType:()=>Fd,getReconnectionTimeout:()=>It,getStringByteLength:()=>Pn,getSysInfo:()=>Qh,getTerminalType:()=>Hd,getTurnServer:()=>nm,getUint32Version:()=>ba,getValueType:()=>me,getViewListFromView:()=>Ts,glog:()=>jd,ipv4ToUint32:()=>Es,isArray:()=>de,isAudioWorkletSupported:()=>tm,isBoolean:()=>ue,isConstructor:()=>fs,isEmpty:()=>Ra,isFunction:()=>Q,isLangChinese:()=>Et,isMediaStreamTrack:()=>em,isNumber:()=>ee,isObject:()=>ct,isOverseaSdkAppId:()=>hs,isPlainObject:()=>$e,isPortrait:()=>Na,isPromise:()=>_s,isRemoteTrack:()=>fi,isString:()=>z,isUndefined:()=>E,loadImage:()=>gs,logVisibilityState:()=>ya,ms2bytes:()=>Zh,ms2samples:()=>Jd,performanceNow:()=>U,promiseAny:()=>ms,samples2ms:()=>Wd,setNetworkType:()=>Aa,stringify:()=>dt,stringifyIncludeValue:()=>Ca});var ci={};Fr(ci,{ANDROID_VERSION:()=>jo,CHROME_MAJOR_VERSION:()=>Ut,CHROME_VERSION:()=>Rn,EDGE_VERSION:()=>cn,EDG_MAJOR_VERSION:()=>Xo,EDG_VERSION:()=>dn,FIREFOX_MAJOR_VERSION:()=>Ko,FIREFOX_VERSION:()=>an,HUAWEI_VERSION:()=>gn,IE_VERSION:()=>ph,IOS_MAIN_VERSION:()=>ts,IOS_VERSION:()=>pt,IPADQQB_VERSION:()=>En,IS_ANDROID:()=>ge,IS_ANDROID_WEBVIEW:()=>qo,IS_ANY_SAFARI:()=>ai,IS_CHROME:()=>cr,IS_CHROME_OS:()=>vd,IS_CHROMIUM_BASE:()=>bi,IS_EDG:()=>ir,IS_EDGE:()=>tr,IS_ELECTRON:()=>Qo,IS_FIREFOX:()=>q,IS_HEADLESS_CHROME:()=>Yo,IS_HUAWEI:()=>fh,IS_HUAWEIBROWSER:()=>Zr,IS_IE:()=>bd,IS_IE8:()=>mh,IS_IOS:()=>Be,IS_IOS_13_OR_14:()=>ea,IS_IOS_15_1:()=>Zo,IS_IPAD:()=>er,IS_IPADQQB:()=>Qr,IS_IPAD_PRO:()=>Jo,IS_IPHONE:()=>oi,IS_IPOD:()=>Nd,IS_LINUX:()=>Yr,IS_LOCAL:()=>it,IS_MAC:()=>tt,IS_MACQQB:()=>zr,IS_MIBROWSER:()=>qr,IS_MQQB:()=>nr,IS_NATIVE_ANDROID:()=>hh,IS_OLD_ANDROID:()=>lh,IS_OPPOBROWSER:()=>or,IS_SAFARI:()=>Ke,IS_SAFARI_15_1:()=>Eh,IS_SAMSUNGBROWSER:()=>es,IS_SOGOU:()=>jr,IS_SOGOUM:()=>Jr,IS_TBS:()=>et,IS_UCBROWSER:()=>zo,IS_VIVOBROWSER:()=>ar,IS_WECHAT:()=>rr,IS_WIN:()=>wt,IS_WQQB:()=>Xr,IS_WX:()=>_h,IS_X5MQQB:()=>sr,IS_XWEB:()=>Kr,MACQQB_VERSION:()=>fn,MI_VERSION:()=>Tn,MQQB_VERSION:()=>Zi,OPPO_VERSION:()=>In,SAFARI_VERSION:()=>dr,SAMSUNG_VERSION:()=>Sn,SOGOUM_VERSION:()=>un,SOGOU_VERSION:()=>ln,TBS_VERSION:()=>hn,USER_AGENT:()=>Ze,VIVO_VERSION:()=>An,WECHAT_VERSION:()=>pn,WQQB_VERSION:()=>_n,XWEB_VERSION:()=>mn,browserInfo:()=>mt,getBrowserInfo:()=>Od,getChromeMajorVersion:()=>Vt,getOSName:()=>Cn,getOSString:()=>rs,getUserAgentData:()=>is,isFunction:()=>Cd,isLocalStorageEnabled:()=>Bt,isUndefined:()=>yd});var Cd=r=>typeof r=="function",yd=r=>typeof r=="undefined",Ze=typeof navigator=="undefined"?"":navigator.userAgent,J=r=>new RegExp(r,"i").test(Ze),he=r=>{if(J(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=Ze.match(i);if(e&&e[1])return e[1]}return""},Wo=r=>{if(J(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=Ze.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Ad=/AppleWebKit\/([\d.]+)/i.exec(Ze),uh=Ad?parseFloat(Ad[1]):NaN,er=J("iPad"),Jo=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&J("Macintosh"),oi=J("iPhone")&&!er,Nd=J("iPod"),Be=oi||er||Nd||Jo,ge=J("Android"),jo=function(){if(ge){let r=Ze.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}(),lh=ge&&J("webkit")&&jo<2.3,hh=ge&&jo<5&&uh<537,q=J("Firefox"),an=he("Firefox"),Ko=Wo("Firefox"),tr=J("Edge"),cn=he("Edge"),ir=J("Edg"),dn=he("Edg"),Xo=Wo("Edg"),Jr=J("SogouMobileBrowser"),un=he("SogouMobileBrowser"),jr=J("MetaSr\\s"),ln=he("MetaSr\\s"),et=J("TBS"),hn=he("TBS"),Kr=J("XWEB"),mn=he("XWEB"),mh=J("MSIE\\s8\\.0"),bd=J("MSIE\\/\\d+"),ph=function(){if(bd){let r=/MSIE\s(\d+)\.\d/.exec(Ze),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(Ze)&&/rv:11.0/.test(Ze)&&(i=11),i}return NaN}(),rr=J("(micromessenger|webbrowser)"),pn=he("MicroMessenger"),sr=!et&&J("MQQBrowser")&&J("COVC"),nr=!et&&J("MQQBrowser")&&!J("COVC"),Zi=nr||sr?he("MQQBrowser"):"",Xr=!et&&J(" QQBrowser"),_n=he(" QQBrowser"),zr=!et&&J("QQBrowserLite"),fn=he("QQBrowserLite"),Qr=!et&&J("MQBHD"),En=he("MQBHD"),wt=J("Windows"),tt=!Be&&J("MAC OS X"),Yr=!ge&&J("Linux"),vd=J("CrOS"),_h=J("MicroMessenger"),zo=J("UCBrowser"),Qo=J("Electron"),qr=J("MiuiBrowser"),Tn=he("MiuiBrowser"),Zr=J("HuaweiBrowser"),fh=J("Huawei"),gn=he("HuaweiBrowser"),es=J("SamsungBrowser"),Sn=he("SamsungBrowser"),or=J("HeyTapBrowser"),In=he("HeyTapBrowser"),ar=J("VivoBrowser"),An=he("VivoBrowser"),Vt=()=>Wo("Chrome"),bi=J("Chrome"),cr=!tr&&!jr&&!Jr&&!et&&!Kr&&!ir&&!Xr&&!qr&&!Zr&&!es&&!or&&!ar&&bi,Yo=J("HeadlessChrome"),Ut=Vt(),Rn=he("Chrome"),Ke=!bi&&!nr&&!sr&&!zr&&!Qr&&J("Safari"),ai=Ke||Be,dr=he("Version"),qo=/Android.*(wv|.0.0.0)/.test(Ze),pt=(()=>{if(Jo)return dr;if(Be){let r=Ze.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),ts=Number(pt.split(".")[0]),Eh=dr==="15.1",Zo=pt==="15.1",ea=(()=>{let r=Number(pt.split(".")[0]);return r===14||r===13})(),it=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Bt=(()=>{let r;return()=>{if(yd(r))try{r=!!window.localStorage}catch(i){r=!1}return r}})(),mt=Od();function Od(){let r=new Map([[q,["Firefox",an]],[ir,["Edg",dn]],[cr,["Chrome",Rn]],[Ke,["Safari",dr]],[et,["TBS",hn]],[Kr,["XWEB",mn]],[rr&&oi,["WeChat",pn]],[Xr,["QQ(Win)",_n]],[nr,["QQ(Mobile)",Zi]],[sr,["QQ(Mobile X5)",Zi]],[zr,["QQ(Mac)",fn]],[Qr,["QQ(iPad)",En]],[qr,["MI",Tn]],[Zr,["HW",gn]],[es,["Samsung",Sn]],[or,["OPPO",In]],[ar,["VIVO",An]],[tr,["EDGE",cn]],[Jr,["SogouMobile",un]],[jr,["Sogou",ln]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var Me=null;function is(){return p(this,null,function*(){if(Me)return Me;if(!navigator.userAgentData||!Cd(navigator.userAgentData.getHighEntropyValues))return null;try{return Me=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Me}catch(r){return null}})}var Rd=new Map([[ge,"Android"],[Be,"iOS"],[wt,"Windows"],[tt,"MacOS"],[Yr,"Linux"],[vd,"ChromeOS"]]),Cn=function(){return Rd.get(!0)?Rd.get(!0):Me?Me.platform:"unknown"},rs=()=>{let r=Cn();return r+=`/${mt.name}/${Ke?mt.version:mt.version.split(".")[0]}`,Me!=null&&Me.platformVersion&&(r+=`/${Me.platformVersion}`),Me!=null&&Me.architecture&&(r+=`/${Me.architecture}`),r};var _a={};Fr(_a,{AUDIO_MUTE_BIT:()=>Dn,AUDIO_STAT_BIT:()=>li,AUX_STAT_BIT:()=>Di,AUX_STREAM_MSID:()=>aa,BACKEND_ENV:()=>On,BASE_DOC_URL:()=>_t,BASE_HOST:()=>yn,CAPABILITIES_KEYS:()=>Ln,CLASS_NAME:()=>wh,CLOUD_CONSOLE_URL:()=>gh,DATA_FREEZE_TIMING:()=>Mn,DOC_URL:()=>Sh,DTLS_STATE_UNKNOWN:()=>st,ENV_NAME:()=>$t,EXCHANGE_SDP_TIMEOUT:()=>ha,INTERVAL:()=>Li,IS_WORKER:()=>ur,IS_WORKLET:()=>ss,KIBANA_EVENT:()=>Le,LOCAL_STREAM_PUBLISH_STATE:()=>Md,LOGGER_CMD_TYPE:()=>di,LOGGER_DOMAIN:()=>sa,LOGGER_DOMAIN_OVERSEA:()=>na,LOG_LEVEL:()=>rt,LOG_LEVEL_NAME:()=>Uh,MAIN_STREAM_MSID:()=>cs,MICROPHONE_COMMUNICATIONS:()=>Vh,MICROPHONE_DEFAULT:()=>Mi,NAME:()=>h,NETWORK_TYPE:()=>os,NOT_SUPPORTED_H264:()=>ki,PAUSED_RETRY_COUNT:()=>ma,PEERCONNECTION_CONNECTING_TIMEOUT:()=>ds,PEER_CONNECTION_STATE:()=>se,PEER_LEAVE_REASON:()=>pa,RAF:()=>ls,RECOVER_CAPTURE_INTERVAL:()=>mr,REMOTE_STREAM_TYPE_AUX:()=>da,REMOTE_STREAM_TYPE_MAIN:()=>ca,RENDER_FREEZE_TIMING:()=>Mh,RIC:()=>ft,SCHEDULE_DOMAIN:()=>nt,SCHEDULE_TIMEOUT:()=>Ph,SDP_SEMANTICS_PLAN_B:()=>lr,SDP_SEMANTICS_UNIFIED_PLAN:()=>hi,SECOND_HOST:()=>ia,SIGNAL_PING_PONG_INTERVAL:()=>Ah,SIGNAL_PING_TIMEOUT:()=>Ih,SIGNAL_RECONNECTION_COUNT:()=>Dh,SMALL_STAT_BIT:()=>as,SPEAKER_DEFAULT:()=>us,STORAGE_EXPIRES_TIME:()=>Nn,STREAM_TYPE_BIG:()=>Lh,STREAM_TYPE_SMALL:()=>xh,SUBSCRIBE_SMALL_RETRY_COUNT:()=>hr,SYNC_USER_LIST_INTERVAL:()=>kh,Scene:()=>Ht,Switch:()=>Dd,THIRD_HOST:()=>ra,TIMEOUT:()=>mi,TRANSPORT_DIRECTION:()=>j,TRTC_ERROR_ASSISTANCE:()=>oa,TRTC_QUALITY_BAD:()=>bh,TRTC_QUALITY_DISCONNECTED:()=>Oh,TRTC_QUALITY_EXCELLENT:()=>Ch,TRTC_QUALITY_GOOD:()=>yh,TRTC_QUALITY_POOR:()=>Nh,TRTC_QUALITY_UNKNOWN:()=>Rh,TRTC_QUALITY_VERY_BAD:()=>vh,UPDATE_OFFER_TIMEOUT:()=>la,VIDEO_MUTE_BIT:()=>kn,VIDEO_STAT_BIT:()=>ui,audioProfileMap:()=>bn,getRetryCount:()=>Ft,getScriptDir:()=>Th,innerVersion:()=>vi,loggerProxy:()=>ns,screenProfileMap:()=>vn,setLoggerProxy:()=>Oi,setRetryCount:()=>ua,setVersion:()=>ta,version:()=>Se,videoProfileMap:()=>Xe});var vi="4.15.00.1600",Se="5.0.0";function ta(r){Se=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));vi=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var ur=typeof importScripts!="undefined",ss=typeof registerProcessor!="undefined",Th=()=>{let r=ur?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},ns="",Oi=r=>ns=r,yn="web.sdk.qcloud.com",ia="web.sdk.tencent.cn",ra="web.sdk.cloud.tencent.cn",gh="https://console.cloud.tencent.com/trtc",_t=`https://${yn}/trtc/webrtc/v5/doc`,Sh=`${_t}/zh-cn/`,sa="https://yun.tim.qq.com",na="https://apisgp.my-imcloud.com",oa="trtc_error_assistance",di={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},$t={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},rt=(o=>(o[o.TRACE=0]="TRACE",o[o.DEBUG=1]="DEBUG",o[o.INFO=2]="INFO",o[o.WARN=3]="WARN",o[o.ERROR=4]="ERROR",o[o.NONE=5]="NONE",o))(rt||{}),Ih=18e3,Ah=2e3,os={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Nn=7*24*3600*1e3,Dd=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(Dd||{}),bn={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Xe={"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}},vn={"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"},j={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},On={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ht=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ht||{}),ui=1,as=2,Di=4,li=8,Dn=64,kn=16,cs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",aa="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",ca=h.MAIN,da=h.AUXILIARY,Rh=0,Ch=1,yh=2,Nh=3,bh=4,vh=5,Oh=6,st="unknown",se={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},kd=1/0;function ua(r){kd=r}function Ft(){return kd}var Dh=30,Le={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"},kh=1e4,la=1e4,ha=1e4,hi="unified-plan",lr="plan-b",ki=1028,Md=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Md||{}),Mn=500,Mh=1e3,Lh=h.BIG,xh=h.SMALL,ds=10*1e3,nt={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},Ph=2e3,wh={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ma=5,Mi="default",us=Mi,Vh="communications",Uh=Object.keys(rt),pa=["normal leave","timeout leave","kick","role change"],hr=10,mr=2e3,ft="ric",ls="raf",Li="interval",mi="timeout",Ln=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];var ot=1e8;function Gt({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((n,o)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);n({data:a})}catch(a){n({data:s.response})}else o({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function fa(r){return p(this,null,function*(){let i=U(),e=JSON.stringify(r);try{if(!CompressionStream||e.length<=2800)return e;let s=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(s)).blob()).arrayBuffer();return A.debug(`compressJSON ${e.length} -> ${a.byteLength} ${U()-i}ms`),a}catch(t){return e}})}var v={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"},Ee={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}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${me(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}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${me(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 Ld=(r,i)=>i?`${_t}/${r}/${i}`:`${_t}/${r}/index.html`;var Bh=()=>{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(oa);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 O(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,n="",o="",a="";Q(Ee[i])?n=Ee[i](e):z(Ee[i])&&(n=Ee[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Bh();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(Q(d[i])?a=d[i](e):z(d[i])&&(a=d[i]));let l=n;return Et()&&(c&&c[i]&&(Q(c[i])?o=c[i](e):z(c[i])&&(o=c[i])),o&&(s?l=`${o}
|
|
6
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${
|
|
5
|
+
`}});var qc=Lt(ri=>{var Wi=Al(),Vp=Cl();ri.write=Vp;ri.parse=Wi.parse;ri.parseParams=Wi.parseParams;ri.parseFmtpConfig=Wi.parseFmtpConfig;ri.parsePayloads=Wi.parsePayloads;ri.parseRemoteCandidates=Wi.parseRemoteCandidates;ri.parseImageAttributes=Wi.parseImageAttributes;ri.parseSimulcastStreamList=Wi.parseSimulcastStreamList});import GL from"webrtc-adapter";var cl=ve(Ve());var Td=(O=>(O[O.INVALID_PARAMETER=4096]="INVALID_PARAMETER",O[O.INVALID_OPERATION=4097]="INVALID_OPERATION",O[O.NOT_SUPPORTED=4098]="NOT_SUPPORTED",O[O.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",O[O.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",O[O.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",O[O.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",O[O.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",O[O.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",O[O.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",O[O.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",O[O.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",O[O.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",O[O.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",O[O.CLIENT_BANNED=16448]="CLIENT_BANNED",O[O.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",O[O.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",O[O.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",O[O.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",O[O.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",O[O.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",O[O.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",O[O.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",O[O.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",O[O.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",O[O.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",O[O.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",O[O.API_CALL_ABORTED=16461]="API_CALL_ABORTED",O[O.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",O[O.UNKNOWN=65535]="UNKNOWN",O))(Td||{}),S=Td;var ah=function(r){for(let i in S)if(S[i]===r)return i;return"UNKNOWN"},Go=class extends Error{constructor({name:e="RtcError",message:t,code:s=S.UNKNOWN,extraCode:n=0,constraint:o}){let a=`<${ah(s)} 0x${s.toString(16)}>`,c=`${t}${o?` constraint: ${o}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=s,this.extraCode=n,this.name=e,this.message=c,this.constraint=o,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},C=Go;var Sd=new Date().getTime(),Wo=0,Id=function(r){Sd=r,Wo=Sd-new Date().getTime();let i=new Date;i.setTime(r),A.info(`baseTime from server: ${i} offset: ${Wo}`)},Hr=function(){return new Date().getTime()+Wo},sn=function(){let r=new Date;return r.setTime(Hr()),r.toLocaleString()};var De={};Br(De,{bytes2ms:()=>Xh,convertObjectNumberToInt:()=>wn,copyProperties:()=>Kh,deepClone:()=>hr,deepMerge:()=>Ht,fibonacci:()=>lr,formatedTime:()=>rm,getAbilityConfigUrl:()=>wd,getConstructorName:()=>xn,getContainerFromElement:()=>tm,getEnv:()=>jh,getInternalVersion:()=>Yh,getLoggerUrl:()=>hi,getMuteStateFromFlag:()=>_i,getNetworkType:()=>Bd,getNumNetworkType:()=>mr,getReconnectionTimeout:()=>St,getStringByteLength:()=>Pn,getTurnServer:()=>em,getUint32Version:()=>ba,getValueType:()=>he,getViewListFromView:()=>_s,glog:()=>Gd,ipv4ToUint32:()=>ps,isArray:()=>de,isAudioWorkletSupported:()=>qh,isBoolean:()=>ue,isConstructor:()=>ms,isEmpty:()=>Ca,isFunction:()=>Q,isLangChinese:()=>ft,isMediaStreamTrack:()=>zh,isNumber:()=>re,isObject:()=>at,isOverseaSdkAppId:()=>ds,isPlainObject:()=>Be,isPortrait:()=>Na,isPromise:()=>hs,isRemoteTrack:()=>pi,isString:()=>z,isUndefined:()=>E,loadImage:()=>fs,ms2bytes:()=>Qh,ms2samples:()=>Fd,performanceNow:()=>B,promiseAny:()=>us,samples2ms:()=>Hd,setNetworkType:()=>Ra,stringify:()=>ct,stringifyIncludeValue:()=>ya});var na={};Br(na,{AUDIO_MUTE_BIT:()=>ln,AUDIO_STAT_BIT:()=>ai,AUX_STAT_BIT:()=>Ni,AUX_STREAM_MSID:()=>qo,BACKEND_ENV:()=>un,BASE_DOC_URL:()=>lt,BASE_HOST:()=>nn,CAPABILITIES_KEYS:()=>pn,CLASS_NAME:()=>Nh,CLOUD_CONSOLE_URL:()=>dh,DATA_FREEZE_TIMING:()=>mn,DOC_URL:()=>uh,DTLS_STATE_UNKNOWN:()=>et,ENV_NAME:()=>xt,EXCHANGE_SDP_TIMEOUT:()=>ia,INTERVAL:()=>Oi,IS_WORKER:()=>Qi,IS_WORKLET:()=>Gr,KIBANA_EVENT:()=>Me,LOCAL_STREAM_PUBLISH_STATE:()=>Cd,LOGGER_CMD_TYPE:()=>ni,LOGGER_DOMAIN:()=>Xo,LOGGER_DOMAIN_OVERSEA:()=>Qo,LOG_LEVEL:()=>Ze,LOG_LEVEL_NAME:()=>vh,MAIN_STREAM_MSID:()=>jr,MICROPHONE_COMMUNICATIONS:()=>bh,MICROPHONE_DEFAULT:()=>vi,NAME:()=>h,NETWORK_TYPE:()=>on,NOT_SUPPORTED_H264:()=>bi,PAUSED_RETRY_COUNT:()=>ra,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Kr,PEER_CONNECTION_STATE:()=>se,PEER_LEAVE_REASON:()=>sa,RAF:()=>Qr,RECOVER_CAPTURE_INTERVAL:()=>Yi,REMOTE_STREAM_TYPE_AUX:()=>Zo,REMOTE_STREAM_TYPE_MAIN:()=>Yo,RENDER_FREEZE_TIMING:()=>Ah,RIC:()=>ht,SCHEDULE_DOMAIN:()=>tt,SCHEDULE_TIMEOUT:()=>yh,SDP_SEMANTICS_PLAN_B:()=>zi,SDP_SEMANTICS_UNIFIED_PLAN:()=>ci,SECOND_HOST:()=>jo,SIGNAL_PING_PONG_INTERVAL:()=>hh,SIGNAL_PING_TIMEOUT:()=>lh,SIGNAL_RECONNECTION_COUNT:()=>Sh,SMALL_STAT_BIT:()=>Jr,SPEAKER_DEFAULT:()=>Xr,STORAGE_EXPIRES_TIME:()=>an,STREAM_TYPE_BIG:()=>Rh,STREAM_TYPE_SMALL:()=>Ch,SUBSCRIBE_SMALL_RETRY_COUNT:()=>qi,SYNC_USER_LIST_INTERVAL:()=>Ih,Scene:()=>Pt,Switch:()=>Ad,THIRD_HOST:()=>Ko,TIMEOUT:()=>di,TRANSPORT_DIRECTION:()=>J,TRTC_ERROR_ASSISTANCE:()=>zo,TRTC_QUALITY_BAD:()=>Eh,TRTC_QUALITY_DISCONNECTED:()=>Th,TRTC_QUALITY_EXCELLENT:()=>ph,TRTC_QUALITY_GOOD:()=>_h,TRTC_QUALITY_POOR:()=>fh,TRTC_QUALITY_UNKNOWN:()=>mh,TRTC_QUALITY_VERY_BAD:()=>gh,UPDATE_OFFER_TIMEOUT:()=>ta,VIDEO_MUTE_BIT:()=>hn,VIDEO_STAT_BIT:()=>oi,audioProfileMap:()=>cn,getRetryCount:()=>wt,getScriptDir:()=>ch,innerVersion:()=>Fr,loggerProxy:()=>Wr,screenProfileMap:()=>dn,setLoggerProxy:()=>yi,setRetryCount:()=>ea,setVersion:()=>Jo,version:()=>Te,videoProfileMap:()=>Ke});var Fr="4.15.00.1600",Te="5.0.0";function Jo(r){Te=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));Fr=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Qi=typeof importScripts!="undefined",Gr=typeof registerProcessor!="undefined",ch=()=>{let r=Qi?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},Wr="",yi=r=>Wr=r,nn="web.sdk.qcloud.com",jo="web.sdk.tencent.cn",Ko="web.sdk.cloud.tencent.cn",dh="https://console.cloud.tencent.com/trtc",lt=`https://${nn}/trtc/webrtc/v5/doc`,uh=`${lt}/zh-cn/`,Xo="https://yun.tim.qq.com",Qo="https://apisgp.my-imcloud.com",zo="trtc_error_assistance",ni={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},xt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Ze=(o=>(o[o.TRACE=0]="TRACE",o[o.DEBUG=1]="DEBUG",o[o.INFO=2]="INFO",o[o.WARN=3]="WARN",o[o.ERROR=4]="ERROR",o[o.NONE=5]="NONE",o))(Ze||{}),lh=18e3,hh=2e3,on={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},an=7*24*3600*1e3,Ad=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(Ad||{}),cn={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Ke={"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}},dn={"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"},J={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},un={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Pt=(e=>(e.LIVE="live",e.RTC="rtc",e))(Pt||{}),oi=1,Jr=2,Ni=4,ai=8,ln=64,hn=16,jr="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",qo="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Yo=h.MAIN,Zo=h.AUXILIARY,mh=0,ph=1,_h=2,fh=3,Eh=4,gh=5,Th=6,et="unknown",se={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Rd=1/0;function ea(r){Rd=r}function wt(){return Rd}var Sh=30,Me={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"},Ih=1e4,ta=1e4,ia=1e4,ci="unified-plan",zi="plan-b",bi=1028,Cd=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Cd||{}),mn=500,Ah=1e3,Rh=h.BIG,Ch=h.SMALL,Kr=10*1e3,tt={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},yh=2e3,Nh={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ra=5,vi="default",Xr=vi,bh="communications",vh=Object.keys(Ze),sa=["normal leave","timeout leave","kick","role change"],qi=10,Yi=2e3,ht="ric",Qr="raf",Oi="interval",di="timeout",pn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function Vt({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((n,o)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);n({data:a})}catch(a){n({data:s.response})}else o({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function oa(r){return p(this,null,function*(){let i=B(),e=JSON.stringify(r);try{if(!CompressionStream||e.length<=2800)return e;let s=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(s)).blob()).arrayBuffer();return A.debug(`compressJSON ${e.length} -> ${a.byteLength} ${B()-i}ms`),a}catch(t){return e}})}var it=1e8;var v={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"},Ee={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}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${he(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}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${he(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 dr={};Br(dr,{ANDROID_VERSION:()=>da,CHROME_MAJOR_VERSION:()=>Bt,CHROME_VERSION:()=>Mn,EDGE_VERSION:()=>fn,EDG_MAJOR_VERSION:()=>la,EDG_VERSION:()=>En,FIREFOX_MAJOR_VERSION:()=>ua,FIREFOX_VERSION:()=>_n,HUAWEI_VERSION:()=>vn,IE_VERSION:()=>Lh,IOS_MAIN_VERSION:()=>os,IOS_VERSION:()=>_t,IPADQQB_VERSION:()=>yn,IS_ANDROID:()=>Ce,IS_ANDROID_WEBVIEW:()=>_a,IS_ANY_SAFARI:()=>li,IS_CHROME:()=>ar,IS_CHROME_OS:()=>Od,IS_CHROMIUM_BASE:()=>ki,IS_EDG:()=>tr,IS_EDGE:()=>er,IS_ELECTRON:()=>ma,IS_FIREFOX:()=>Y,IS_HEADLESS_CHROME:()=>pa,IS_HUAWEI:()=>Ph,IS_HUAWEIBROWSER:()=>ss,IS_IE:()=>vd,IS_IE8:()=>Mh,IS_IOS:()=>Ue,IS_IOS_13_OR_14:()=>Ea,IS_IOS_15_1:()=>fa,IS_IPAD:()=>zr,IS_IPADQQB:()=>is,IS_IPAD_PRO:()=>ca,IS_IPHONE:()=>Di,IS_IPOD:()=>bd,IS_LINUX:()=>Nn,IS_LOCAL:()=>ot,IS_MAC:()=>pt,IS_MACQQB:()=>ts,IS_MIBROWSER:()=>rs,IS_MQQB:()=>sr,IS_NATIVE_ANDROID:()=>kh,IS_OLD_ANDROID:()=>Dh,IS_OPPOBROWSER:()=>nr,IS_SAFARI:()=>Xe,IS_SAFARI_15_1:()=>wh,IS_SAMSUNGBROWSER:()=>ns,IS_SOGOU:()=>Yr,IS_SOGOUM:()=>qr,IS_TBS:()=>nt,IS_UCBROWSER:()=>ha,IS_VIVOBROWSER:()=>or,IS_WECHAT:()=>ir,IS_WIN:()=>ui,IS_WQQB:()=>es,IS_WX:()=>xh,IS_X5MQQB:()=>rr,IS_XWEB:()=>Zr,MACQQB_VERSION:()=>Cn,MI_VERSION:()=>bn,MQQB_VERSION:()=>Zi,OPPO_VERSION:()=>Dn,SAFARI_VERSION:()=>cr,SAMSUNG_VERSION:()=>On,SOGOUM_VERSION:()=>gn,SOGOU_VERSION:()=>Tn,TBS_VERSION:()=>Sn,USER_AGENT:()=>st,VIVO_VERSION:()=>kn,WECHAT_VERSION:()=>An,WQQB_VERSION:()=>Rn,XWEB_VERSION:()=>In,browserInfo:()=>mt,getBrowserInfo:()=>Dd,getChromeMajorVersion:()=>Ut,getOSName:()=>Ln,getOSString:()=>cs,getOSType:()=>Vh,getTerminalType:()=>ga,getUserAgentData:()=>as,isLocalStorageEnabled:()=>$t});var st=typeof navigator=="undefined"?"":navigator.userAgent,j=r=>new RegExp(r,"i").test(st),me=r=>{if(j(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=st.match(i);if(e&&e[1])return e[1]}return""},aa=r=>{if(j(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=st.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},yd=/AppleWebKit\/([\d.]+)/i.exec(st),Oh=yd?parseFloat(yd[1]):NaN,zr=j("iPad"),ca=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&j("Macintosh"),Di=j("iPhone")&&!zr,bd=j("iPod"),Ue=Di||zr||bd||ca,Ce=j("Android"),da=function(){if(Ce){let r=st.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}(),Dh=Ce&&j("webkit")&&da<2.3,kh=Ce&&da<5&&Oh<537,Y=j("Firefox"),_n=me("Firefox"),ua=aa("Firefox"),er=j("Edge"),fn=me("Edge"),tr=j("Edg"),En=me("Edg"),la=aa("Edg"),qr=j("SogouMobileBrowser"),gn=me("SogouMobileBrowser"),Yr=j("MetaSr\\s"),Tn=me("MetaSr\\s"),nt=j("TBS"),Sn=me("TBS"),Zr=j("XWEB"),In=me("XWEB"),Mh=j("MSIE\\s8\\.0"),vd=j("MSIE\\/\\d+"),Lh=function(){if(vd){let r=/MSIE\s(\d+)\.\d/.exec(st),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(st)&&/rv:11.0/.test(st)&&(i=11),i}return NaN}(),ir=j("(micromessenger|webbrowser)"),An=me("MicroMessenger"),rr=!nt&&j("MQQBrowser")&&j("COVC"),sr=!nt&&j("MQQBrowser")&&!j("COVC"),Zi=sr||rr?me("MQQBrowser"):"",es=!nt&&j(" QQBrowser"),Rn=me(" QQBrowser"),ts=!nt&&j("QQBrowserLite"),Cn=me("QQBrowserLite"),is=!nt&&j("MQBHD"),yn=me("MQBHD"),ui=j("Windows"),pt=!Ue&&j("MAC OS X"),Nn=!Ce&&j("Linux"),Od=j("CrOS"),xh=j("MicroMessenger"),ha=j("UCBrowser"),ma=j("Electron"),rs=j("MiuiBrowser"),bn=me("MiuiBrowser"),ss=j("HuaweiBrowser"),Ph=j("Huawei"),vn=me("HuaweiBrowser"),ns=j("SamsungBrowser"),On=me("SamsungBrowser"),nr=j("HeyTapBrowser"),Dn=me("HeyTapBrowser"),or=j("VivoBrowser"),kn=me("VivoBrowser"),Ut=()=>aa("Chrome"),ki=j("Chrome"),ar=!er&&!Yr&&!qr&&!nt&&!Zr&&!tr&&!es&&!rs&&!ss&&!ns&&!nr&&!or&&ki,pa=j("HeadlessChrome"),Bt=Ut(),Mn=me("Chrome"),Xe=!ki&&!sr&&!rr&&!ts&&!is&&j("Safari"),li=Xe||Ue,cr=me("Version"),_a=/Android.*(wv|.0.0.0)/.test(st),_t=(()=>{if(ca)return cr;if(Ue){let r=st.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),os=Number(_t.split(".")[0]),wh=cr==="15.1",fa=_t==="15.1",Ea=(()=>{let r=Number(_t.split(".")[0]);return r===14||r===13})(),ot=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",$t=(()=>{let r;return()=>{if(E(r))try{r=!!window.localStorage}catch(i){r=!1}return r}})(),mt=Dd();function Dd(){let r=new Map([[Y,["Firefox",_n]],[tr,["Edg",En]],[ar,["Chrome",Mn]],[Xe,["Safari",cr]],[nt,["TBS",Sn]],[Zr,["XWEB",In]],[ir&&Di,["WeChat",An]],[es,["QQ(Win)",Rn]],[sr,["QQ(Mobile)",Zi]],[rr,["QQ(Mobile X5)",Zi]],[ts,["QQ(Mac)",Cn]],[is,["QQ(iPad)",yn]],[rs,["MI",bn]],[ss,["HW",vn]],[ns,["Samsung",On]],[nr,["OPPO",Dn]],[or,["VIVO",kn]],[er,["EDGE",fn]],[qr,["SogouMobile",gn]],[Yr,["Sogou",Tn]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var Le=null;function as(){return p(this,null,function*(){if(Le)return Le;if(!navigator.userAgentData||!Q(navigator.userAgentData.getHighEntropyValues))return null;try{return Le=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Le}catch(r){return null}})}var Nd=new Map([[Ce,"Android"],[Ue,"iOS"],[ui,"Windows"],[pt,"MacOS"],[Nn,"Linux"],[Od,"ChromeOS"]]),Ln=function(){return Nd.get(!0)?Nd.get(!0):Le?Le.platform:"unknown"},cs=()=>{let r=Ln();return r+=`/${mt.name}/${Xe?mt.version:mt.version.split(".")[0]}`,Le!=null&&Le.platformVersion&&(r+=`/${Le.platformVersion}`),Le!=null&&Le.architecture&&(r+=`/${Le.architecture}`),r};function ga(){return Ce?4:Di?2:zr?3:pt?12:ui?5:Nn?13:1}function Vh(){return Ce?"Android":Di?"iPhone":zr?"iPad":pt?"Mac":ui?"Windows":Nn?"Linux":"unknown"}var kd=(r,i)=>i?`${lt}/${r}/${i}`:`${lt}/${r}/index.html`;var Uh=()=>{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(zo);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,n="",o="",a="";Q(Ee[i])?n=Ee[i](e):z(Ee[i])&&(n=Ee[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Uh();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(Q(d[i])?a=d[i](e):z(d[i])&&(a=d[i]));let l=n;return ft()&&(c&&c[i]&&(Q(c[i])?o=c[i](e):z(c[i])&&(o=c[i])),o&&(s?l=`${o}
|
|
6
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${kd("zh-cn",a)}
|
|
7
7
|
|
|
8
8
|
`:l=`${o}
|
|
9
9
|
|
|
10
10
|
`,l+=n)),s&&(l+=`
|
|
11
|
-
Refer to: ${
|
|
12
|
-
`),l}var
|
|
13
|
-
`));function St(r){ue(r)&&r!==ga&&(ga=r,A.info(`setIsNeedToSchedule ${r}`))}g.on("28",()=>St(!0));g.on("63",()=>St(!0));g.on("84",()=>St(!0));g.on("201",r=>{r.state==="RECONNECTING"&&St(!0)});g.on("202",r=>{r.state==="RECONNECTING"&&St(!0)});function Wh(r,i,e){let t=performance.getEntriesByType("resource"),s=pr(r,h.MAIN),n=pr(r,h.BACKUP),o={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===n)&&a.transferSize>0){let c=a.name===s?h.MAIN:h.BACKUP,d=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=Math.round(a.domainLookupEnd-a.domainLookupStart),_=Math.round(a.requestStart-a.secureConnectionStart),T=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),R=Math.round(a.responseEnd-a.responseStart),M=[l,m,_,T,C,R];te.uploadEvent({log:`stat-schedule-net:${d}(${M.join("->")}) ${c}`,userId:i}),o=L(y({},o),{totalCost:d,local:l,dns:m,tcp:T,tls:_,request:C,response:R});break}return o}function Vd(a){return p(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:n,frameWorkType:o}){if(!ga&&Ta)return{isCached:!0,result:Ta};let c={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(r)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(e)),d.append("groupId",String(t)),d.append("sdkVersion",n),d.append("userSig",String(s)),o&&d.append("frameWorkType",String(o));let l=U(),m=yield jh(d,c,i);m.config&&(m.config.loggerDomain&&Oi(m.config.loggerDomain),ue(m.config.scheduleCache)&&St(!m.config.scheduleCache)),c.delta=U()-l;let _=Wh(Number(i),r,l);return Ta=m,{isCached:!1,result:m,detailCost:_}}catch(d){let l=de(d)?d[0]:d,m=ee(l.code)?l.code:0,_=`schedule failed${l.message?`: ${l.message}`:""}`,T=new N({code:S.SCHEDULE_FAILED,extraCode:m,message:O({key:v.JOIN_ROOM_FAILED,data:{error:_,code:m}})});throw A.error(_,m),T}})}var _i={main:"",backup:""};function Sa(r){de(r)?(_i.main=r[0],_i.backup=r[1]):_i.main=r}function pr(r,i=h.MAIN,e=!1){return`https://${_i[i]||Bd(r,i,e)}/api/v1/config`}function Ud(r,i=h.MAIN){return`https://${_i[i]||Bd(r,i)}/api/v1/trtcAutoConf`}function Bd(r,i=h.MAIN,e=!1){if(hs(r))return i===h.MAIN?nt.MAIN_OVERSEA:nt.BACKUP_OVERSEA;let t;return hs(r)?e?t=i===h.MAIN?nt.MAIN_OVERSEA_OLD:nt.BACKUP_OVERSEA_OLD:t=i===h.MAIN?nt.MAIN_OVERSEA:nt.BACKUP_OVERSEA:t=i===h.MAIN?nt.MAIN:nt.BACKUP,t}function Jh(r,i,e){return new Promise((t,s)=>{Gt({url:r,body:i,timeout:e.timeout}).then(n=>{n.data.code===0?t(n.data.data):s({code:n.data.code,message:n.data.msg})}).catch(s)})}var wd=(r,i)=>Tt({retryFunction:Jh,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function jh(r,i,e){return new Promise((t,s)=>{let n=null;ms([wd(o=>i.count[0]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=o.message,n||(c>=2&&(d[0]=pr(e,h.MAIN,!0)),a())})(pr(e,h.MAIN),r,{get timeout(){return _r(2+i.count[0])*1e3}}),wd(o=>i.count[1]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=o.message,n||(c>=2&&(d[0]=pr(e,h.BACKUP,!0)),a())})(pr(e,h.BACKUP),r,{get timeout(){return _r(2+i.count[1])*1e3}})]).then(o=>{n=o,t(n)}).catch(s)})}var Xh="trtc_env",zh=function(){return new URLSearchParams(location.search).get(Xh)||""},hs=r=>Number(r)<14e8,pi=function(r,i){let e;ns?e=ns:e=hs(r)?na:sa;let t=Math.floor(Math.random()*Hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`};function Hd(){return ge?4:oi?2:er?3:tt?12:wt?5:Yr?13:1}function Fd(){return ge?"Android":oi?"iPhone":er?"iPad":tt?"Mac":wt?"Windows":Yr?"Linux":"unknown"}var ps="unknown";function Ia(){if(ps!=="unknown")return ps;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();return s==="slow-2"&&(s="2g"),t&&(ps=Gd(t,s)),ps}function Gd(r,i){if(os[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Aa(r){ps=Gd(r)}function Er(){return os[Ia()]}var Qh=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:Hd(),uint32_device_type:0,str_os_verion:Fd(),uint32_link_type:1,str_client_version:vi,uint32_net_type:os[Ia()],ua:navigator.userAgent,version:""}}}};function Yh(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 qh(r,i=48e3){return Wd(r/4,i)}function Wd(r,i=48e3){return r*1e3/i}function Zh(r,i=48e3){return Jd(r,i)*4}function Jd(r,i=48e3){return r*i/1e3}var jd=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Et=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},$e=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 _r(r,i=1,e=1){return r<=1?e:_r(r-1,e,i+e)}function It(r){return r>8?30*1e3:_r(r)*1e3}function me(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Q=r=>typeof r=="function",E=r=>typeof r=="undefined",z=r=>typeof r=="string",ee=r=>typeof r=="number",ue=r=>typeof r=="boolean",ct=r=>me(r)==="object",de=r=>me(r)==="array",em=r=>me(r)==="MediaStreamTrack".toLowerCase(),fi=r=>r.isRemote,_s=r=>me(r)==="promise",fs=r=>Q(r)&&r.prototype.constructor===r,xn=r=>fs(r)?r.prototype.constructor.name:"",tm=typeof AudioWorkletNode!="undefined";function ms(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(n=>{t.push(n),t.length===r.length&&e(t)})})})}function U(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var $d=r=>+r<10?`0${r}`:r,im=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=$d(e[1])+$d(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},rm=Object.prototype.hasOwnProperty,{toString:mf}=Object.prototype;function Ra(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($e(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(rm.call(r,i))return!1;return!0}}return!1}function Ei(r,i){return{userId:i,hasAudio:!!(r&li),hasVideo:!!(r&ui),hasAuxiliary:!!(r&Di),hasSmall:!!(r&as),audioMuted:!!(r&Dn),videoMuted:!!(r&kn),audioAvailable:!!(r&li)&&!(r&Dn),videoAvailable:!!(r&ui)&&!(r&kn)}}function sm(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 nm(r){let i={urls:`turn:${r.url}`};return!E(r.username)&&!E(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",E(r.credentialType)||(i.credentialType=r.credentialType)),i}function Es(r,i=!0){if(!z(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 Wt=function(r,i,e,t){if(!(ct(r)&&ct(i)))return 0;let s=0,n=Object.keys(i),o;for(let a=0,c=n.length;a<c;a++)if(o=n[a],!(E(i[o])||e&&e.includes(o)))if(ct(r[o])&&ct(i[o]))s+=Wt(r[o],i[o],e,t);else{if(t&&t.includes(i[o]))continue;r[o]!==i[o]&&(r[o]=fr(i[o]),s+=1)}return s};function fr(r){if(de(r)){let i=[];return r.forEach((e,t)=>{i[t]=fr(e)}),i}if(ct(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=fr(r[e])}),i}return r}var Ts=r=>{let i=[];if(de(r))i=[...r];else if(z(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},om=r=>z(r)?document.getElementById(r):r,am=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),cm=()=>am.format(new Date);function dt(r,{keysToInclude:i,keysToExclude:e}){try{if(de(r))return`[${r.map(o=>dt(o,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!$e(r)||!de(i)&&!de(e))return JSON.stringify(r);let t={},s=new Set(i),n=new Set(e);return Object.keys(r).forEach(o=>{(n.size===0&&s.has(o)||s.size===0&&!n.has(o))&&(t[o]=$e(r[o])||de(r[o])?JSON.parse(dt(r[o],{keysToExclude:e,keysToInclude:i})):r[o])}),JSON.stringify(t)}catch(t){return"{}"}}function Ca(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),dt(r,{keysToInclude:e})}function Pn(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var ya=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})(),Na=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},gs=r=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(z(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=e})}),ba=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},wn=r=>(Object.keys(r).forEach(i=>{ee(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):($e(r[i])||de(r[i]))&&wn(r[i])}),r);var dm=Object.prototype.hasOwnProperty;var Kd=r=>typeof r=="undefined";var Xd=r=>typeof r=="boolean";var um=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 zd(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(um(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(dm.call(r,i))return!1;return!0}}return!1}var Tr=class{constructor(i){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Xd(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,Kd(this.userId)||zd(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 f=xi;var lm="%cTRTC%c%s",hm="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",mm="display: inline",pm=!(Be||ge||Yo),va=class{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!ur&&!ss&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){g.on(f.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&rt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),g.on(f.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),g.once(f.JOIN_FAILED,()=>{this.startUpload()}),g.on(f.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:n})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,logs:[t]})});else if(z(t.userId)&&ee(t.sdkAppId)){let{userId:s,sdkAppId:n}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,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 n=0;n<s.length;n++){let{userId:o,sdkAppId:a,logs:c}=s[n];yield this.uploadLogWithRetry(JSON.stringify({timestamp:on(),sdkAppId:String(a),userId:o,version:Se,log:c.map(d=>d.log).join(`
|
|
14
|
-
`)}),a),c.forEach(d=>d.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Tt({retryFunction:()=>Gt({url:pi(e,di.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(Wr());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}] <${rt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(rt[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(z(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,n){var a;if(e.unshift(this.getPrefix(i)),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,d)=>`${c} ${this.logChunkToString(d)}`.trim(),""),level:i,userId:s,sdkAppId:n,forAllJoinedClients:t}),i<this._logLevel)return;let o=((a=rt[i])==null?void 0:a.toLowerCase())||"info";pm?console[o](lm,hm,mm,...e):console[o](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new Tr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;rt[t]&&(this._logLevelToUpload=t)}},A=new va;var _m=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)})},Ss=_m;var Oa=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Bt())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=localStorage.getItem(t);if(!s)return!1;let n=JSON.parse(s);if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!Bt())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){A.warn(i)}}getItem(i){if(!Bt())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){A.warn(e)}}setItem(i,e){if(!!Bt())try{let t={expiresIn:Date.now()+Nn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){A.warn(t)}}deleteItem(i){if(!Bt())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(!!Bt())try{localStorage.clear()}catch(i){A.warn(i)}}},Jt=new Oa;var zt={};Fr(zt,{HTTPS_API:()=>Om,IS_GET_CAPABILITIES_SUPPORTED:()=>wa,IS_GET_SETTINGS_SUPPORTED:()=>Rt,IS_SEI_SUPPORTED:()=>Vi,IS_SPC_SUPPORTED:()=>Cs,basis:()=>Mm,checkSystemRequirementsInternal:()=>Bn,decodeSupportStatus:()=>Un,encodeSupportStatus:()=>La,getBrowserInfo:()=>ym,getDisplayResolution:()=>ou,isAddTransceiverSupported:()=>ze,isBrowserSupported:()=>xa,isGetReceiversSupported:()=>wi,isGetSendersSupported:()=>Sr,isGetTransceiversSupported:()=>At,isGetUserMediaSupported:()=>au,isMediaDevicesSupported:()=>Vn,isMediaSessionSupported:()=>lu,isMediaStreamTrackProcessorSupported:()=>Nm,isReplaceTrackSupported:()=>Pa,isScreenCaptureApiAvailable:()=>As,isSelectedCandidatePair:()=>Ti,isSetParametersSupported:()=>ys,isSmallStreamAPISupported:()=>du,isSmallStreamSupported:()=>Rs,isStopTransceiverSupported:()=>km,isTRTCSupported:()=>bm,isUnifiedPlanDefault:()=>Dm,isUsedInHttpProtocol:()=>Xt,isWebAudioSupported:()=>cu,isWebCodecSupported:()=>uu,isWebCodecsSupported:()=>nu,isWebRTCSupported:()=>Va,isWebTransportSupported:()=>hu});var Ma=ve(ru(),1);var Y={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Cm=new Map([[q,["Firefox",an]],[ir,["Edg",dn]],[cr,["Chrome",Rn]],[Ke,["Safari",dr]],[et,["TBS",hn]],[Kr,["XWEB",mn]],[rr&&oi,["WeChat",pn]],[Xr,["QQ(Win)",_n]],[nr,["QQ(Mobile)",Zi]],[sr,["QQ(Mobile X5)",Zi]],[zr,["QQ(Mac)",fn]],[Qr,["QQ(iPad)",En]],[qr,["MI",Tn]],[Zr,["HW",gn]],[es,["Samsung",Sn]],[or,["OPPO",In]],[ar,["VIVO",An]],[tr,["EDGE",cn]],[Jr,["SogouMobile",un]],[jr,["Sogou",ln]]]);function ym(){let r=Cm.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var xa=function(){return!(zo||tr||ir&&Xo<80||q&&Ko<56)},nu=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},Vn=function(){if(!navigator.mediaDevices)return Xt()||A.error(Ee.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},su=!1;function Xt(){return location.protocol==="http:"&&!it?(su||A.error(O({key:v.NOT_SUPPORTED_HTTP})),su=!0,!0):!1}var Nm=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},La=function(){return p(this,null,function*(){if(Y.detail.isH264EncodeSupported||Y.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Y.detail.isH264EncodeSupported,isVp8EncodeSupported:Y.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let n=s.captureStream(0);return t.addTrack(n.getVideoTracks()[0],n),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),Y.detail.isH264EncodeSupported=i,Y.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:Y.detail.isH264EncodeSupported,isVp8EncodeSupported:Y.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Un=function(){return p(this,null,function*(){if(Y.detail.isH264DecodeSupported&&Y.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Y.detail.isH264DecodeSupported,isVp8DecodeSupported:Y.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}}})},Bn=function(){return p(this,null,function*(){if(Y.result)return Y;let r=xa(),i=Va(),e=nu(),t=Vn(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield La(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield Un();if(!s||!n){let c=yield La();s=c.isH264EncodeSupported,n=c.isVp8EncodeSupported}if(s&&o&&(or||ar||qo)&&!et&&Vt()<79){let{encode:c,decode:d}=yield vm();s=c,o=d}return Y.result=r&&i&&t&&(s||n)&&(o||a),Y.detail.isBrowserSupported=r,Y.detail.isWebRTCSupported=i,Y.detail.isWebCodecsSupported=e,Y.detail.isMediaDevicesSupported=t,Y.detail.isScreenShareSupported=As(),Y.detail.isSmallStreamSupported=Rs(),Y.detail.isH264EncodeSupported=s,Y.detail.isVp8EncodeSupported=n,Y.detail.isH264DecodeSupported=o,Y.detail.isVp8DecodeSupported=a,Y.result||A.error(`${navigator.userAgent} ${Ca(Y.detail,!1)}`),Lm(),Y})},bm=function(){return Y.result},As=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)};function vm(){return p(this,null,function*(){return new Promise(r=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),s=t.getContext("2d");t.width=640,t.height=480;let n=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},33),o=-1,a=-1;e=()=>{clearInterval(o),clearInterval(n),clearTimeout(a),d.close(),l.close(),c.getTracks().forEach(R=>R.stop())},a=setTimeout(()=>{e(),r(i)},3*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),l=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",R=>l.addIceCandidate(R.candidate)),l.addEventListener("icecandidate",R=>d.addIceCandidate(R.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield l.setRemoteDescription(m);let _=yield l.createAnswer(),T=Ma.default.parse(_.sdp),C=T.media[0].rtp.findIndex(R=>R.codec==="H264");T.media[0].rtp=[T.media[0].rtp[C]],T.media[0].fmtp=T.media[0].fmtp.filter(R=>R.payload===T.media[0].rtp[0].payload),T.media[0].rtcpFb&&(T.media[0].rtcpFb=T.media[0].rtcpFb.filter(R=>R.payload===T.media[0].rtp[0].payload)),_.sdp=Ma.default.write(T),yield l.setLocalDescription(_),yield d.setRemoteDescription(_),o=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let R=yield d.getStats(),M=yield l.getStats();i.encode||R.forEach(re=>{re.type==="outbound-rtp"&&re.mediaType===h.VIDEO&&re.framesEncoded>0&&(i.encode=!0)}),i.decode||M.forEach(re=>{re.type==="inbound-rtp"&&re.mediaType===h.VIDEO&&re.framesDecoded>0&&(i.decode=!0)})}),500)}catch(t){e(),A.warn(t),r(i)}}))})}var Om=(r,i,e)=>{location.protocol==="http:"&&!it&&(r[i]=()=>{throw new N({code:S.INVALID_OPERATION,message:Ee.NOT_SUPPORTED_HTTP})})},Ti=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(ue(r.selected)&&!r.selected):!1};function ou(){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 au(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function cu(){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 du(){return"captureStream"in HTMLCanvasElement.prototype}function Rs(){return rr||Be||Ut&&Ut<63?!1:!!(xa()&&du())}var Dm=function(){if(E(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:hi}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function wi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Sr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function At(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ze(){return ts===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Cs=(()=>!(!ze()||bi&&Ut<74))();function km(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Pa(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function ys(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Sr()}var Rt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,wa=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Vi="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Vt()>=86,Va=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function uu(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return E(window.AudioDecoder)||(r.AudioDecoder=!0),E(window.AudioEncoder)||(r.AudioEncoder=!0),E(window.VideoDecoder)||(r.VideoDecoder=!0),E(window.VideoEncoder)||(r.VideoEncoder=!0),E(window.ImageDecoder)||(r.ImageDecoder=!0),r}function lu(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function hu(){return!E(window.WebTransport)}function Mm(){let r={browser:`${mt.name}/${mt.version}`,os:Cn(),displayResolution:ou(),isScreenShareSupported:As(),isWebRTCSupported:Va(),isGetUserMediaSupported:au(),isWebAudioSupported:cu(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:uu(),isMediaSessionSupported:lu(),isWebTransportSupported:hu()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var mu="checkResult";function Lm(){Jt.setItem(mu,{ua:navigator.userAgent,checkResult:Y})}(function(){Xt();let i=Jt.getItem(mu);i&&i.ua===navigator.userAgent&&(Y=i.checkResult),Bn()})();var _u=ve(Ue(),1);var pu=Symbol("instance"),Qf=Symbol("abortCtrl"),$n=Symbol("cacheResult"),Ns=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Os.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},bs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function xm(r){return typeof r=="object"&&r&&"then"in r}var vs=new Map;function oe(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=vs.get(t)||[];vs.has(t)||vs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=P.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[$n]:Promise.resolve(d[$n]);d.state instanceof Ns&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;Array.isArray(r)?r.length==0?d.state instanceof Ns&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new bs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(l=new bs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`));let m=M=>{if(e.fail&&e.fail.call(this,M),e.sync){if(e.ignoreError)return M;throw M}else return e.ignoreError?Promise.resolve(M):Promise.reject(M)};if(l)return m(l);let _=d.state,T=new Ns(_,i,o);Os.call(d,T);let C=M=>{var re;return d[$n]=M,T.aborted||(Os.call(d,i),(re=e.success)===null||re===void 0||re.call(this,d[$n])),M},R=M=>{let re=M instanceof Error?M.message:String(M);return Os.call(d,_,M),m(new bs(d._state,`action '${o}' failed :${re}`,M instanceof Error?M:new Error(re)))};try{let M=a.apply(this,c);return xm(M)?M.then(C).catch(R):e.sync?C(M):Promise.resolve(C(M))}catch(M){return R(M)}}}}var Pm=(()=>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 Os(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(P.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var P=class extends _u.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=P.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[pu];s?this.name=s.name+"-"+s.count++:t[pu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=vs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);vs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=P.instances.get(i),e||P.instances.set(i,e=new P(i,void 0,Object.create(P.prototype)))):(e=P.instances2.get(i),e||P.instances2.set(i,e=new P(i.constructor.name,void 0,Object.create(P.prototype)))),e}static getState(i){var e;return(e=P.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Pm(P.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Os.call(this,i)}};P.STATECHANGED="stateChanged";P.UPDATEAFSM="updateAFSM";P.INIT="[*]";P.ON="on";P.OFF="off";P.instances=new Map;P.instances2=new WeakMap;var fu=(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)},wm=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Vm=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Ds=class{static generateTaskID(){return this.currentTaskID++}static run(i=mi,e,t){i===Li?t=y({delay:2e3,count:0,backgroundTask:!0},t):i===ft?t=y({delay:1e4,count:0},t):i===ls?t=y({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=y({delay:2e3,count:0,backgroundTask:!0},t),ct(e)&&(t=y(y({},t),e)),Q(i)&&(e=i,i=mi);let s=y({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([`
|
|
11
|
+
Refer to: ${kd("en",a)}
|
|
12
|
+
`),l}var Bh=0,$h=1,Md=2;function Hh({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:n,context:o}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,l=0,m=-1,_=Bh,g=(R,y)=>p(this,null,function*(){let L=o||this;try{let ie=yield r.apply(L,a);l>0&&n&&n.call(this,l),l=0,R(ie)}catch(ie){let W=()=>{clearTimeout(m),l=0,_=Md,y(ie)},en=()=>{_!==Md&&l<(Q(c)?c():c)?(l++,_=$h,Q(t)&&t.call(this,l,W),m=window.setTimeout(()=>{m=-1,g(R,y)},Q(d)?d(l):d)):(W(),Q(s)&&s.call(this,ie))};Q(e)?e.call(this,{error:ie,retry:en,reject:y,retryFuncArgs:a,retriedCount:l}):en()}});return new Promise(g)}}var Et=Hh;var Ld=ve(Ve(),1),Fh=new Ld.default,T=Fh;var Mi=(H=>(H.ROOM_DESTROY="1",H.JOIN_START="21",H.JOIN_SCHEDULE_SUCCESS="22",H.JOIN_SIGNAL_CONNECTION_START="23",H.JOIN_SIGNAL_CONNECTION_END="24",H.JOIN_SEND_CMD="25",H.JOIN_RECEIVED_CMD_RES="26",H.JOIN_SUCCESS="27",H.JOIN_FAILED="28",H.LEAVE_START="51",H.LEAVE_SEND_CMD="52",H.LEAVE_SUCCESS="53",H.PUBLISH_START="61",H.SEND_FIRST_VIDEO_FRAME="62",H.PUBLISH_FAILED="63",H.SUBSCRIBE_START="81",H.SUBSCRIBE_SUCCESS="82",H.SUBSCRIBE_FAILED="84",H.UNSUBSCRIBE_SUCCESS="83",H.LOCAL_TRACK_CAPTURE_START="101",H.LOCAL_TRACK_CAPTURE_SUCCESS="102",H.LOCAL_TRACK_CAPTURE_FAILED="103",H.LOCAL_TRACK_PUBLISHED="104",H.LOCAL_TRACK_UNPUBLISHED="105",H.LOCAL_TRACK_REPLACED="106",H.SWITCH_DEVICE_SUCCESS="107",H.TRACK_MUTED="108",H.TRACK_UNMUTED="109",H.REMOTE_TRACK_SUBSCRIBED="110",H.REMOTE_TRACK_UNSUBSCRIBED="111",H.PLAY_TRACK_START="151",H.PLAYER_STATE_CHANGED="152",H.VIDEO_LOADED_DATA="153",H.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",H.SIGNAL_CONNECTION_STATE_CHANGED="201",H.PEER_CONNECTION_STATE_CHANGED="202",H.SINGLE_CONNECTION_STAT="203",H.SPC_RECONNECTED="204",H.HEARTBEAT_REPORT="251",H.RECEIVED_PUBLISHED_USER_LIST="252",H.REMOTE_PUBLISH_STATE_CHANGED="253",H.AUDIO_LEVEL_INTERVAL="260",H.NETWORK_QUALITY="261",H))(Mi||{});var Ta=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Te,env:xt.QCLOUD,browserVersion:mt.name+mt.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){ot||!A.isAbleToUpload||this._configs.env===xt.QCLOUD&&this.uploadEventToKibana(M(N({},i),{result:"success"}))}logFailedEvent(i){if(ot||!A.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:n}=i,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||S.UNKNOWN};this._configs.env===xt.QCLOUD&&this.uploadEventToKibana(M(N({},o),{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:sn(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Te,log:i};t&&(s.errorInfo=t.message),this.sendRequest(hi(this._configs.sdkAppId,ni.LOG),s)}sendRequest(i,e){if(!A.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}Vt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},ee=new Ta;var Sa=null,Ia=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(tt).map(r=>`<link rel="dns-prefetch" href="https://${r}">`).join(`\r
|
|
13
|
+
`));function Tt(r){ue(r)&&r!==Ia&&(Ia=r,A.info(`setIsNeedToSchedule ${r}`))}T.on("28",()=>Tt(!0));T.on("63",()=>Tt(!0));T.on("84",()=>Tt(!0));T.on("201",r=>{r.state==="RECONNECTING"&&Tt(!0)});T.on("202",r=>{r.state==="RECONNECTING"&&Tt(!0)});function Gh(r,i,e){let t=performance.getEntriesByType("resource"),s=ur(r,h.MAIN),n=ur(r,h.BACKUP),o={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===n)&&a.transferSize>0){let c=a.name===s?h.MAIN:h.BACKUP,d=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=Math.round(a.domainLookupEnd-a.domainLookupStart),_=Math.round(a.requestStart-a.secureConnectionStart),g=Math.round(a.secureConnectionStart-a.connectStart),R=Math.round(a.responseStart-a.requestStart),y=Math.round(a.responseEnd-a.responseStart),L=[l,m,_,g,R,y];ee.uploadEvent({log:`stat-schedule-net:${d}(${L.join("->")}) ${c}`,userId:i}),o=M(N({},o),{totalCost:d,local:l,dns:m,tcp:g,tls:_,request:R,response:y});break}return o}function Pd(a){return p(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:n,frameWorkType:o}){if(!Ia&&Sa)return{isCached:!0,result:Sa};let c={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(r)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(e)),d.append("groupId",String(t)),d.append("sdkVersion",n),d.append("userSig",String(s)),o&&d.append("frameWorkType",String(o));let l=B(),m=yield Jh(d,c,i);m.config&&(m.config.loggerDomain&&yi(m.config.loggerDomain),ue(m.config.scheduleCache)&&Tt(!m.config.scheduleCache)),c.delta=B()-l;let _=Gh(Number(i),r,l);return Sa=m,{isCached:!1,result:m,detailCost:_}}catch(d){let l=de(d)?d[0]:d,m=re(l.code)?l.code:0,_=`schedule failed${l.message?`: ${l.message}`:""}`,g=new C({code:S.SCHEDULE_FAILED,extraCode:m,message:D({key:v.JOIN_ROOM_FAILED,data:{error:_,code:m}})});throw A.error(_,m),g}})}var mi={main:"",backup:""};function Aa(r){de(r)?(mi.main=r[0],mi.backup=r[1]):mi.main=r}function ur(r,i=h.MAIN,e=!1){return`https://${mi[i]||Vd(r,i,e)}/api/v1/config`}function wd(r,i=h.MAIN){return`https://${mi[i]||Vd(r,i)}/api/v1/trtcAutoConf`}function Vd(r,i=h.MAIN,e=!1){if(ds(r))return i===h.MAIN?tt.MAIN_OVERSEA:tt.BACKUP_OVERSEA;let t;return ds(r)?e?t=i===h.MAIN?tt.MAIN_OVERSEA_OLD:tt.BACKUP_OVERSEA_OLD:t=i===h.MAIN?tt.MAIN_OVERSEA:tt.BACKUP_OVERSEA:t=i===h.MAIN?tt.MAIN:tt.BACKUP,t}function Wh(r,i,e){return new Promise((t,s)=>{Vt({url:r,body:i,timeout:e.timeout}).then(n=>{n.data.code===0?t(n.data.data):s({code:n.data.code,message:n.data.msg})}).catch(s)})}var xd=(r,i)=>Et({retryFunction:Wh,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function Jh(r,i,e){return new Promise((t,s)=>{let n=null;us([xd(o=>i.count[0]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=o.message,n||(c>=2&&(d[0]=ur(e,h.MAIN,!0)),a())})(ur(e,h.MAIN),r,{get timeout(){return lr(2+i.count[0])*1e3}}),xd(o=>i.count[1]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=o.message,n||(c>=2&&(d[0]=ur(e,h.BACKUP,!0)),a())})(ur(e,h.BACKUP),r,{get timeout(){return lr(2+i.count[1])*1e3}})]).then(o=>{n=o,t(n)}).catch(s)})}var jh=function(){return new URLSearchParams(location.search).get("trtc_env")||""},ds=r=>Number(r)<14e8,hi=function(r,i){let e;Wr?e=Wr:e=ds(r)?Qo:Xo;let t=Math.floor(Math.random()*Ur(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},ls="unknown";function Bd(){if(ls!=="unknown")return ls;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();return s==="slow-2"&&(s="2g"),t&&(ls=$d(t,s)),ls}function $d(r,i){if(on[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ra(r){ls=$d(r)}function mr(){return on[Bd()]}function Kh(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 Xh(r,i=48e3){return Hd(r/4,i)}function Hd(r,i=48e3){return r*1e3/i}function Qh(r,i=48e3){return Fd(r,i)*4}function Fd(r,i=48e3){return r*i/1e3}var Gd=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},ft=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Be=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 lr(r,i=1,e=1){return r<=1?e:lr(r-1,e,i+e)}function St(r){return r>8?30*1e3:lr(r)*1e3}function he(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Q=r=>typeof r=="function",E=r=>typeof r=="undefined",z=r=>typeof r=="string",re=r=>typeof r=="number",ue=r=>typeof r=="boolean",at=r=>he(r)==="object",de=r=>he(r)==="array",zh=r=>he(r)==="MediaStreamTrack".toLowerCase(),pi=r=>r.isRemote,hs=r=>he(r)==="promise",ms=r=>Q(r)&&r.prototype.constructor===r,xn=r=>ms(r)?r.prototype.constructor.name:"",qh=typeof AudioWorkletNode!="undefined";function us(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(n=>{t.push(n),t.length===r.length&&e(t)})})})}function B(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Ud=r=>+r<10?`0${r}`:r,Yh=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=Ud(e[1])+Ud(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Zh=Object.prototype.hasOwnProperty,{toString:nf}=Object.prototype;function Ca(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(Be(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(Zh.call(r,i))return!1;return!0}}return!1}function _i(r,i){return{userId:i,hasAudio:!!(r&ai),hasVideo:!!(r&oi),hasAuxiliary:!!(r&Ni),hasSmall:!!(r&Jr),audioMuted:!!(r&ln),videoMuted:!!(r&hn),audioAvailable:!!(r&ai)&&!(r&ln),videoAvailable:!!(r&oi)&&!(r&hn)}}function em(r){let i={urls:`turn:${r.url}`};return!E(r.username)&&!E(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",E(r.credentialType)||(i.credentialType=r.credentialType)),i}function ps(r,i=!0){if(!z(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 Ht=function(r,i,e,t){if(!(at(r)&&at(i)))return 0;let s=0,n=Object.keys(i),o;for(let a=0,c=n.length;a<c;a++)if(o=n[a],!(E(i[o])||e&&e.includes(o)))if(at(r[o])&&at(i[o]))s+=Ht(r[o],i[o],e,t);else{if(t&&t.includes(i[o]))continue;r[o]!==i[o]&&(r[o]=hr(i[o]),s+=1)}return s};function hr(r){if(de(r)){let i=[];return r.forEach((e,t)=>{i[t]=hr(e)}),i}if(at(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=hr(r[e])}),i}return r}var _s=r=>{let i=[];if(de(r))i=[...r];else if(z(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},tm=r=>z(r)?document.getElementById(r):r,im=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),rm=()=>im.format(new Date);function ct(r,{keysToInclude:i,keysToExclude:e}){try{if(de(r))return`[${r.map(o=>ct(o,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Be(r)||!de(i)&&!de(e))return JSON.stringify(r);let t={},s=new Set(i),n=new Set(e);return Object.keys(r).forEach(o=>{(n.size===0&&s.has(o)||s.size===0&&!n.has(o))&&(t[o]=Be(r[o])||de(r[o])?JSON.parse(ct(r[o],{keysToExclude:e,keysToInclude:i})):r[o])}),JSON.stringify(t)}catch(t){return"{}"}}function ya(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),ct(r,{keysToInclude:e})}function Pn(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Na=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},fs=r=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(z(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=e})}),ba=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},wn=r=>(Object.keys(r).forEach(i=>{re(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Be(r[i])||de(r[i]))&&wn(r[i])}),r);var sm=Object.prototype.hasOwnProperty;var Wd=r=>typeof r=="undefined";var Jd=r=>typeof r=="boolean";var nm=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 jd(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(nm(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(sm.call(r,i))return!1;return!0}}return!1}var pr=class{constructor(i){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Jd(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,Wd(this.userId)||jd(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 f=Mi;var om="%cTRTC%c%s",am="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",cm="display: inline",dm=!(Ue||Ce||pa),va=class{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!Qi&&!Gr&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(f.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&Ze[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(f.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(f.JOIN_FAILED,()=>{this.startUpload()}),T.on(f.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:n})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,logs:[t]})});else if(z(t.userId)&&re(t.sdkAppId)){let{userId:s,sdkAppId:n}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,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 n=0;n<s.length;n++){let{userId:o,sdkAppId:a,logs:c}=s[n];yield this.uploadLogWithRetry(JSON.stringify({timestamp:sn(),sdkAppId:String(a),userId:o,version:Te,log:c.map(d=>d.log).join(`
|
|
14
|
+
`)}),a),c.forEach(d=>d.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Et({retryFunction:()=>Vt({url:hi(e,ni.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(Hr());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}] <${Ze[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(Ze[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(z(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,n){var a;if(e.unshift(this.getPrefix(i)),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,d)=>`${c} ${this.logChunkToString(d)}`.trim(),""),level:i,userId:s,sdkAppId:n,forAllJoinedClients:t}),i<this._logLevel)return;let o=((a=Ze[i])==null?void 0:a.toLowerCase())||"info";dm?console[o](om,am,cm,...e):console[o](...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 pr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Ze[t]&&(this._logLevelToUpload=t)}},A=new va;var um=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)})},Es=um;var Oa=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!$t())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=localStorage.getItem(t);if(!s)return!1;let n=JSON.parse(s);if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!$t())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){A.warn(i)}}getItem(i){if(!$t())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){A.warn(e)}}setItem(i,e){if(!!$t())try{let t={expiresIn:Date.now()+an,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){A.warn(t)}}deleteItem(i){if(!$t())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(!!$t())try{localStorage.clear()}catch(i){A.warn(i)}}},Ft=new Oa;var jt={};Br(jt,{HTTPS_API:()=>Cm,IS_GET_CAPABILITIES_SUPPORTED:()=>wa,IS_GET_SETTINGS_SUPPORTED:()=>At,IS_SEI_SUPPORTED:()=>Ei,IS_SPC_SUPPORTED:()=>Is,basis:()=>bm,checkSystemRequirementsInternal:()=>Bn,decodeSupportStatus:()=>Un,encodeSupportStatus:()=>La,getBrowserInfo:()=>Sm,getDisplayResolution:()=>ru,isAddTransceiverSupported:()=>Qe,isBrowserSupported:()=>xa,isGetReceiversSupported:()=>xi,isGetSendersSupported:()=>fr,isGetTransceiversSupported:()=>It,isGetUserMediaSupported:()=>su,isMediaDevicesSupported:()=>Vn,isMediaSessionSupported:()=>cu,isMediaStreamTrackProcessorSupported:()=>Im,isReplaceTrackSupported:()=>Pa,isScreenCaptureApiAvailable:()=>Ts,isSelectedCandidatePair:()=>fi,isSetParametersSupported:()=>As,isSmallStreamAPISupported:()=>ou,isSmallStreamSupported:()=>Ss,isStopTransceiverSupported:()=>Nm,isTRTCSupported:()=>Am,isUnifiedPlanDefault:()=>ym,isUsedInHttpProtocol:()=>Jt,isWebAudioSupported:()=>nu,isWebCodecSupported:()=>au,isWebCodecsSupported:()=>iu,isWebRTCSupported:()=>Va,isWebTransportSupported:()=>du});var Ma=ve(eu(),1);var q={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Tm=new Map([[Y,["Firefox",_n]],[tr,["Edg",En]],[ar,["Chrome",Mn]],[Xe,["Safari",cr]],[nt,["TBS",Sn]],[Zr,["XWEB",In]],[ir&&Di,["WeChat",An]],[es,["QQ(Win)",Rn]],[sr,["QQ(Mobile)",Zi]],[rr,["QQ(Mobile X5)",Zi]],[ts,["QQ(Mac)",Cn]],[is,["QQ(iPad)",yn]],[rs,["MI",bn]],[ss,["HW",vn]],[ns,["Samsung",On]],[nr,["OPPO",Dn]],[or,["VIVO",kn]],[er,["EDGE",fn]],[qr,["SogouMobile",gn]],[Yr,["Sogou",Tn]]]);function Sm(){let r=Tm.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var xa=function(){return!(ha||er||tr&&la<80||Y&&ua<56)},iu=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},Vn=function(){if(!navigator.mediaDevices)return Jt()||A.error(Ee.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},tu=!1;function Jt(){return location.protocol==="http:"&&!ot?(tu||A.error(D({key:v.NOT_SUPPORTED_HTTP})),tu=!0,!0):!1}var Im=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},La=function(){return p(this,null,function*(){if(q.detail.isH264EncodeSupported||q.detail.isVp8EncodeSupported)return{isH264EncodeSupported:q.detail.isH264EncodeSupported,isVp8EncodeSupported:q.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let n=s.captureStream(0);return t.addTrack(n.getVideoTracks()[0],n),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),q.detail.isH264EncodeSupported=i,q.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:q.detail.isH264EncodeSupported,isVp8EncodeSupported:q.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Un=function(){return p(this,null,function*(){if(q.detail.isH264DecodeSupported&&q.detail.isVp8DecodeSupported)return{isH264DecodeSupported:q.detail.isH264DecodeSupported,isVp8DecodeSupported:q.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}}})},Bn=function(){return p(this,null,function*(){if(q.result)return q;let r=xa(),i=Va(),e=iu(),t=Vn(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield La(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield Un();if(!s||!n){let c=yield La();s=c.isH264EncodeSupported,n=c.isVp8EncodeSupported}if(s&&o&&(nr||or||_a)&&!nt&&Ut()<79){let{encode:c,decode:d}=yield Rm();s=c,o=d}return q.result=r&&i&&t&&(s||n)&&(o||a),q.detail.isBrowserSupported=r,q.detail.isWebRTCSupported=i,q.detail.isWebCodecsSupported=e,q.detail.isMediaDevicesSupported=t,q.detail.isScreenShareSupported=Ts(),q.detail.isSmallStreamSupported=Ss(),q.detail.isH264EncodeSupported=s,q.detail.isVp8EncodeSupported=n,q.detail.isH264DecodeSupported=o,q.detail.isVp8DecodeSupported=a,q.result||A.error(`${navigator.userAgent} ${ya(q.detail,!1)}`),vm(),q})},Am=function(){return q.result},Ts=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)};function Rm(){return p(this,null,function*(){return new Promise(r=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),s=t.getContext("2d");t.width=640,t.height=480;let n=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},33),o=-1,a=-1;e=()=>{clearInterval(o),clearInterval(n),clearTimeout(a),d.close(),l.close(),c.getTracks().forEach(y=>y.stop())},a=setTimeout(()=>{e(),r(i)},3*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),l=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",y=>l.addIceCandidate(y.candidate)),l.addEventListener("icecandidate",y=>d.addIceCandidate(y.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield l.setRemoteDescription(m);let _=yield l.createAnswer(),g=Ma.default.parse(_.sdp),R=g.media[0].rtp.findIndex(y=>y.codec==="H264");g.media[0].rtp=[g.media[0].rtp[R]],g.media[0].fmtp=g.media[0].fmtp.filter(y=>y.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(y=>y.payload===g.media[0].rtp[0].payload)),_.sdp=Ma.default.write(g),yield l.setLocalDescription(_),yield d.setRemoteDescription(_),o=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let y=yield d.getStats(),L=yield l.getStats();i.encode||y.forEach(ie=>{ie.type==="outbound-rtp"&&ie.mediaType===h.VIDEO&&ie.framesEncoded>0&&(i.encode=!0)}),i.decode||L.forEach(ie=>{ie.type==="inbound-rtp"&&ie.mediaType===h.VIDEO&&ie.framesDecoded>0&&(i.decode=!0)})}),500)}catch(t){e(),A.warn(t),r(i)}}))})}var Cm=(r,i,e)=>{location.protocol==="http:"&&!ot&&(r[i]=()=>{throw new C({code:S.INVALID_OPERATION,message:Ee.NOT_SUPPORTED_HTTP})})},fi=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(ue(r.selected)&&!r.selected):!1};function ru(){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 su(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function nu(){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 ou(){return"captureStream"in HTMLCanvasElement.prototype}function Ss(){return ir||Ue||Bt&&Bt<63?!1:!!(xa()&&ou())}var ym=function(){if(E(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:ci}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function xi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function fr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function It(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Qe(){return os===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Is=(()=>!(!Qe()||ki&&Bt<74))();function Nm(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Pa(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function As(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&fr()}var At=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,wa=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ei="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Ut()>=86,Va=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function au(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return E(window.AudioDecoder)||(r.AudioDecoder=!0),E(window.AudioEncoder)||(r.AudioEncoder=!0),E(window.VideoDecoder)||(r.VideoDecoder=!0),E(window.VideoEncoder)||(r.VideoEncoder=!0),E(window.ImageDecoder)||(r.ImageDecoder=!0),r}function cu(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function du(){return!E(window.WebTransport)}function bm(){let r={browser:`${mt.name}/${mt.version}`,os:Ln(),displayResolution:ru(),isScreenShareSupported:Ts(),isWebRTCSupported:Va(),isGetUserMediaSupported:su(),isWebAudioSupported:nu(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:au(),isMediaSessionSupported:cu(),isWebTransportSupported:du()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var uu="checkResult";function vm(){Ft.setItem(uu,{ua:navigator.userAgent,checkResult:q})}(function(){Jt();let i=Ft.getItem(uu);i&&i.ua===navigator.userAgent&&(q=i.checkResult),Bn()})();var hu=ve(Ve(),1);var lu=Symbol("instance"),Ff=Symbol("abortCtrl"),$n=Symbol("cacheResult"),Rs=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Ns.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Cs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Om(r){return typeof r=="object"&&r&&"then"in r}var ys=new Map;function oe(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=ys.get(t)||[];ys.has(t)||ys.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=w.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[$n]:Promise.resolve(d[$n]);d.state instanceof Rs&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;Array.isArray(r)?r.length==0?d.state instanceof Rs&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Cs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(l=new Cs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`));let m=L=>{if(e.fail&&e.fail.call(this,L),e.sync){if(e.ignoreError)return L;throw L}else return e.ignoreError?Promise.resolve(L):Promise.reject(L)};if(l)return m(l);let _=d.state,g=new Rs(_,i,o);Ns.call(d,g);let R=L=>{var ie;return d[$n]=L,g.aborted||(Ns.call(d,i),(ie=e.success)===null||ie===void 0||ie.call(this,d[$n])),L},y=L=>{let ie=L instanceof Error?L.message:String(L);return Ns.call(d,_,L),m(new Cs(d._state,`action '${o}' failed :${ie}`,L instanceof Error?L:new Error(ie)))};try{let L=a.apply(this,c);return Om(L)?L.then(R).catch(y):e.sync?R(L):Promise.resolve(R(L))}catch(L){return y(L)}}}}var Dm=(()=>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 Ns(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(w.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var w=class extends hu.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=w.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[lu];s?this.name=s.name+"-"+s.count++:t[lu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=ys.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);ys.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=w.instances.get(i),e||w.instances.set(i,e=new w(i,void 0,Object.create(w.prototype)))):(e=w.instances2.get(i),e||w.instances2.set(i,e=new w(i.constructor.name,void 0,Object.create(w.prototype)))),e}static getState(i){var e;return(e=w.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Dm(w.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Ns.call(this,i)}};w.STATECHANGED="stateChanged";w.UPDATEAFSM="updateAFSM";w.INIT="[*]";w.ON="on";w.OFF="off";w.instances=new Map;w.instances2=new WeakMap;var mu=(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)},km=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Mm=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),bs=class{static generateTaskID(){return this.currentTaskID++}static run(i=di,e,t){i===Oi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===ht?t=N({delay:1e4,count:0},t):i===Qr?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),at(e)&&(t=N(N({},t),e)),Q(i)&&(e=i,i=di);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([`
|
|
15
15
|
let timerID = null;
|
|
16
16
|
self.onmessage = function (e) {
|
|
17
17
|
if (e.data === 'start') {
|
|
@@ -22,96 +22,25 @@ Refer to: ${Ld("en",a)}
|
|
|
22
22
|
clearInterval(timerID);
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
|
-
`],{type:"application/javascript"})));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=
|
|
25
|
+
`],{type:"application/javascript"})));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=B(),t,s=()=>{if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=mu(s,{timeout:i.delay})};return i.ricID=mu(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=B(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=B()-e,e=B(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=B()-e,t>=i.delay&&(e=B()-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 n=()=>{if(document.hidden){let o=B()-e;o>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-o)}};document.addEventListener("visibilitychange",n),i.onVisibilitychange=n,document.hidden&&n()}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:n,onVisibilitychange:o,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Mm(s),n&&km(n),o&&document.removeEventListener("visibilitychange",o),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}};bs.taskMap=new Map,bs.currentTaskID=1;var Z=bs;var Xf={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 xe={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};var Kt={};Br(Kt,{create:()=>Pe,remove:()=>pe});var vs=new WeakMap;function Pe(r,i){vs.has(r)||vs.set(r,[]);let e=vs.get(r),s={add:(n,o)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,n,o)),i.addEventListener(n,o)):(e.push(i.off.bind(i,n,o)),i.on(n,o)),s)};return s}function pe(r){let i=vs.get(r);i&&(i.forEach(e=>e()),vs.delete(r))}var Xt=class extends w{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=ra,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){return this._state==="PLAYING"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return p(this,null,function*(){if(!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=D({key:v.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:S.PLAY_NOT_ALLOWED,message:t})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.element.remove(),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():fa?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Pe(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(){T.on(f.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&pe(this.track)}unbindEvents(){this.element&&pe(this.element),this.unbindTrackEvents(),T.off(f.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){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),Ue&&(this._interval=Z.run(di,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){let{code:s,message:n}=this.element.error;this._log.error(`${this.kind} player error observed. code: ${s} message: ${n} userAgent: ${navigator.userAgent}`),ee.uploadEvent({log:`stat-${this.kind}-${Me.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error})}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(xe.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(xe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(xe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(xe.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};b([oe([],"PLAYING",{sync:!0})],Xt.prototype,"handlePlaying",1),b([oe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Xt.prototype,"handlePaused",1),b([oe([],"STOPPED",{sync:!0})],Xt.prototype,"handleStopped",1);var Qt="trtc_autoplay",Ua=`${Qt}_mask`,Er=`${Qt}_wrapper`,_u=`${Qt}_header`,Ba=`${Qt}_content`,Hn=`${Qt}_action_wrapper`,$a=`${Qt}_question`,Ha=`${Qt}_collapse`,Fn=`${Qt}_action_confirm`,fu=`${Qt}_detail`,Eu="#2473E8",Ga="dialog",Lm=`${Ga}-show`,xm=`${Ga}-1`,Pm=`${Ga}-2`,gu=!1,Wa=()=>!!document.querySelector(`.${Er}`),Su=`${lt}/${ft()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Tu=`<br><a href='${Su}' target='_blank'>${ft()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,wm=`${ft()?`\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${Tu}`:`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. ${Tu}`}`,Fa=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(ft()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!gu){let i=document.createElement("style");i.innerHTML=`.${Ua}{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;}.${Ua} div:not(.${Hn}){display:block !important;}.${Er}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Er} a{color:${Eu};}.${_u}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Ba}{margin:8px 0;}.${Hn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Ha}{margin-right:auto;cursor:pointer}.${$a}{height:100%;line-height:16px;cursor:pointer;}.${Fn}{margin-left:8px;color:#fff;background:${Eu};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Fn}:hover{opacity:0.9;}.${Ha},.${Fn},.${Ba},.${$a}{font-size:14px;}@media screen and (max-width:750px){.${Er}{width:80vw;}}`,document.head.appendChild(i),gu=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Ua}"><div class='${Er}'><div class='${_u}'>${location.host}</div><div class='${Ba}'>${this.content}</div><div class='${fu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${wm}</div><div class='${Hn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Fn,e.innerText=ft()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=$a,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
26
|
<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">
|
|
27
27
|
<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"/>
|
|
28
28
|
<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"/>
|
|
29
29
|
<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"/>
|
|
30
30
|
</svg>
|
|
31
|
-
`,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=Ha,s.innerText=`${Et()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let n=i.content.firstChild,o=n.querySelector(`.${Hn}`);return o.appendChild(s),o.appendChild(t),o.appendChild(e),n}addDiaLog(){Wa()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Ir}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),te.uploadEvent({log:Um}))}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"),g.emit(f.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${gu}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||te.uploadEvent({log:Bm}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ru,"_blank"),this._isQuestionClicked||te.uploadEvent({log:$m}),this._isQuestionClicked=!0}},Cu=Fa;var ut=class extends Yt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}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){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!Wa()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let n=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}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)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(){var e;super.stop(),(e=this.canvas)==null||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(xe.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function gi(r,i){return p(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),A.info("worklet addModule success")}catch(e){throw A.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Ui=new window.AudioContext({sampleRate:48e3}),Gn=()=>{Ui.state==="suspended"?(Ui.resume(),document.addEventListener("click",Gn)):Ui.state==="interrupted"?Ui.resume():document.removeEventListener("click",Gn)};document.addEventListener("click",Gn);Ui.onstatechange=()=>{A.info(`context state: ${Ui.state}`),Gn()};var we=r=>Ui;var Fm=1,Gm=0,Wn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=A.createLogger({id:"kv"});i&&(g.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?Jn.START_MICROPHONE:Ja.START_CAMERA,cost:t})}),g.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?Jn.START_MICROPHONE:Ja.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:ba(this.version||Se),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,n])=>({uint32_item_key:s,uint32_item_value:n}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var n;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((n=this.distributionMap)==null?void 0:n.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,o=0;if(ee(t))o=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){o=c;break}n.set(o,(n.get(o)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Fm,useUV:!1}),e)){let n=+String(i).slice(-3);n<800&&n>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;ee(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code),this.addEnum({key:i,value:Gm,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},ja=(W=>(W[W.enterRoom=500700]="enterRoom",W[W.exitRoom=500701]="exitRoom",W[W.switchRole=500702]="switchRole",W[W.destroy=500703]="destroy",W[W.startLocalAudio=500704]="startLocalAudio",W[W.updateLocalAudio=500705]="updateLocalAudio",W[W.stopLocalAudio=500706]="stopLocalAudio",W[W.startLocalVideo=500707]="startLocalVideo",W[W.updateLocalVideo=500708]="updateLocalVideo",W[W.stopLocalVideo=500709]="stopLocalVideo",W[W.startScreenShare=500710]="startScreenShare",W[W.updateScreenShare=500711]="updateScreenShare",W[W.stopScreenShare=500712]="stopScreenShare",W[W.startRemoteVideo=500713]="startRemoteVideo",W[W.updateRemoteVideo=500714]="updateRemoteVideo",W[W.stopRemoteVideo=500715]="stopRemoteVideo",W[W.muteRemoteAudio=500716]="muteRemoteAudio",W[W.setRemoteAudioVolume=500717]="setRemoteAudioVolume",W))(ja||{}),Ka=(n=>(n[n.AudioMixer=550700]="AudioMixer",n[n.AIDenoiser=551700]="AIDenoiser",n[n.VirtualBackground=570700]="VirtualBackground",n[n.Beauty=571700]="Beauty",n[n.Watermark=572700]="Watermark",n))(Ka||{}),Xa=(n=>(n[n.AudioMixer=550701]="AudioMixer",n[n.AIDenoiser=551701]="AIDenoiser",n[n.VirtualBackground=570701]="VirtualBackground",n[n.Beauty=571701]="Beauty",n[n.Watermark=572701]="Watermark",n))(Xa||{}),za=(n=>(n[n.AudioMixer=550702]="AudioMixer",n[n.AIDenoiser=551702]="AIDenoiser",n[n.VirtualBackground=570702]="VirtualBackground",n[n.Beauty=571702]="Beauty",n[n.Watermark=572702]="Watermark",n))(za||{}),Jn=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(Jn||{});var Ja=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(Ja||{});var Wm=new Wn(!0),Bi=new Wn(!1);var B=Wm;var lt=class{constructor(){this.pre=new Set;this.next=new Set;this.connectedNodes=new Set}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.preNodeReconnect(),this.reconnect(),B.addSuccessEvent({key:502701})}catch(t){A.error(t),B.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),B.addSuccessEvent({key:502702})}catch(e){A.error(e),B.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},jn=class extends lt{constructor(e=256){super();this.fftSize=e;this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,s=0,n=0,o=`M${s},${n}`;for(let a=0;a<e.length;a++)n=e[a]/128*100/2,o+=`L${s},${n}`,s+=t;return o}},Ms=class{constructor(){this.source=new lt;this.gain=new lt;this.destination=new lt}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(Jm(i))}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},Ar=class extends Ms{constructor(e){super();this.context=e;this.denoiser=new lt;this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},Kn=class{constructor(){this.audioContext=we("audio-mixer");this.destination=this.audioContext.createMediaStreamDestination();this.inputs=new Set;this.mixWeight=0;this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},yu=new WeakMap;function Jm(r){let i=yu.get(r);if(i)return i;let e=we();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return yu.set(r,i),i}var jm=`
|
|
32
|
-
class VolumeMeter extends AudioWorkletProcessor {
|
|
33
|
-
|
|
34
|
-
super();
|
|
35
|
-
this.volume = 0;
|
|
36
|
-
this.intervalTime = 200;
|
|
37
|
-
this.tick = this.intervalTime;
|
|
38
|
-
this.isStop = false;
|
|
39
|
-
this.cache = [];
|
|
40
|
-
this.sentFirstInfo1 = false;
|
|
41
|
-
this.unmute = false;
|
|
42
|
-
this.port.onmessage = (event) => {
|
|
43
|
-
const { data } = event;
|
|
44
|
-
switch (data.name) {
|
|
45
|
-
case "chunk":
|
|
46
|
-
this.cache.push.apply(this.cache, data.data);
|
|
47
|
-
if (!this.sentFirstInfo1) {
|
|
48
|
-
this.port.postMessage({ cl: data.data.length });
|
|
49
|
-
this.sentFirstInfo1 = true;
|
|
50
|
-
}
|
|
51
|
-
break;
|
|
52
|
-
case "setIntervalTime":
|
|
53
|
-
this.intervalTime = data.intervalTime;
|
|
54
|
-
break;
|
|
55
|
-
case "unmute":
|
|
56
|
-
this.unmute = true;
|
|
57
|
-
break;
|
|
58
|
-
case "stop":
|
|
59
|
-
this.isStop = true;
|
|
60
|
-
break;
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
process(inputs, outputs) {
|
|
65
|
-
const input = inputs[0];
|
|
66
|
-
const output = outputs[0];
|
|
67
|
-
if(!input && !output) {
|
|
68
|
-
return true;
|
|
69
|
-
}
|
|
70
|
-
// if (this.isStop) {
|
|
71
|
-
// return false;
|
|
72
|
-
// }
|
|
73
|
-
const l = output? output[0].length:0;
|
|
74
|
-
const cl = this.cache.length;
|
|
75
|
-
|
|
76
|
-
if (cl > l) {
|
|
77
|
-
output[0].set(this.cache.slice(0, l));
|
|
78
|
-
this.cache = this.cache.slice(l);
|
|
79
|
-
} else if (this.unmute) {
|
|
80
|
-
output[0].set(input[0]);
|
|
81
|
-
}
|
|
82
|
-
const firstChannel = cl > l ? output[0] : input[0];
|
|
83
|
-
if(!firstChannel){
|
|
84
|
-
return true;
|
|
85
|
-
}
|
|
86
|
-
let sum = 0;
|
|
87
|
-
let rms;
|
|
88
|
-
for (let i = 0; i < firstChannel.length; ++i) {
|
|
89
|
-
sum += firstChannel[i] * firstChannel[i];
|
|
90
|
-
}
|
|
91
|
-
rms = Math.sqrt(sum / firstChannel.length);
|
|
92
|
-
this.volume = Math.max(rms, this.volume * 0.95);
|
|
93
|
-
this.tick -= firstChannel.length;
|
|
94
|
-
if (this.tick < 0) {
|
|
95
|
-
this.tick += (this.intervalTime / 1000) * sampleRate;
|
|
96
|
-
this.port.postMessage({ volume: this.volume, cl, l });
|
|
97
|
-
}
|
|
98
|
-
return true;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
registerProcessor("volume-meter", VolumeMeter);
|
|
102
|
-
`,$i=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,g.on(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return $i.workletReady||($i.workletReady=gi($i.audioContext,URL.createObjectURL(new Blob([jm],{type:"application/javascript"})))),$i.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode($i.audioContext,"volume-meter"),this._audioWorkletNode.port.onmessage=i=>{this._volume=i.data.volume||0,console.log(i.data)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){te.logFailedEvent({userId:this._log.userId,eventType:Le.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=we("volume-meter").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}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,g.off(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}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})}},Ls=$i;u(Ls,"audioContext",we("volume-meter")),u(Ls,"workletReady");var Xn=class extends lt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ls(e)}deleteNode(){this._volumeMeter.destroy(),super.deleteNode()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var zn=class extends Ms{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"analyser",new jn);this.volumeMeter=new Xn({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},Rr=class extends Yt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",we("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new zn(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((pt==="15.2"||pt==="15.3"||pt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,this.bindElementEvents()}play(){return p(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(we("player").createAnalyser()),this.setVolume(this._volume),Re(Rr.prototype,this,"play").call(this)})}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return p(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Qn=class extends Rr{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(xe.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Yn=class extends Rr{constructor(e){super(e);u(this,"_sourceElement");u(this,"_code3",!1);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}handleElementEvent(e){var t,s;if(super.handleElementEvent(e),e.type===h.ERROR&&((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)===MediaError.MEDIA_ERR_DECODE){this.emit("code3"),this._code3=!0,this.pipeline.destory(),this.pipeline=new zn(this._log);let n=new lt;n.setNode(we("player").destination),this.pipeline.volumeMeter.init(),this.pipeline.volumeMeter.pipeTo(n)}}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){this._code3||this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(xe.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),pe(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}};var Hi=class extends P{constructor({userId:e,sdkAppId:t,mediaType:s,room:n,PlayerClass:o=s===1?Yn:ut}){var a;super();u(this,"id",Ss());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=n||this.room)==null?void 0:a.userId,remoteUserId:this instanceof He?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof He}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this.log}),this.player.on(xe.PLAYER_STATE_CHANGED,c=>{g.emit(f.PLAYER_STATE_CHANGED,y({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(xe.LOADED_DATA,()=>{g.emit(f.VIDEO_LOADED_DATA,{track:this})}),this.player.on(xe.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.setTrack(c))}))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}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&&!E(t.muted)&&this.setPlayerMute(t.muted),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ut&&(this.player.setObjectFit(this.objectFit),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&&!E(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ut&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof ut&&this.player.setContainer(s)),g.emit(f.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.playerMediaTrack),yield this.player.play(),de(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let s=this.player;if(t&&(s=t),ue(this.mirror)){s.setViewMirror(this.mirror),this.room&&(this.room.videoManager.mirror=!1);return}switch(this.mirror){case"view":{this.room&&(this.room.videoManager.mirror=!1),s.setViewMirror(!0);break}case"publish":{this.room&&(this.room.videoManager.mirror=!0),s.setViewMirror(!0);break}case"both":this.room&&(this.room.videoManager.mirror=!0),s.setViewMirror(!1)}}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((n,o)=>{var a;e.find(c=>o===c)||(n.stop(),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[n,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new ut({id:this.userId||this.id,track:this.playerMediaTrack,container:o,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${n+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let n of s)n.setViewMirror(this.player.mirror),yield n.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),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){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),g.emit(e?f.TRACK_MUTED:f.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):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,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>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 Cu;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)}}getVideoFrame(){return this.player instanceof ut?this.player.getVideoFrame():""}};b([oe([],P.INIT,{sync:!0})],Hi.prototype,"close",1);var Km=Object.prototype.hasOwnProperty,{toString:wT}=Object.prototype;function Xm(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($e(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(Km.call(r,i))return!1;return!0}}return!1}var yt=Xm;var vu=ve(Ue(),1);var bu=r=>i=>i.deviceId===r;var Ps=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Cr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(bu(s.deviceId))){let n=`${this.kind}${this.type}Added`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(bu(s.deviceId))){let n=`${this.kind}${this.type}Removed`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Qa=class extends vu.EventEmitter{constructor(){super();u(this,"audioInputs",new Ps(h.AUDIO));u(this,"videoInputs",new Ps(h.VIDEO));u(this,"audioOutputs",new Ps(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Li,()=>{this.update()},{delay:1e4}))}init(){qn().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield qn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},_e=ss||ur?null:new Qa;function Cr(r){return r.deviceId===r.groupId&&r.groupId===""}function qn(){return p(this,arguments,function*(r=0){if(Xt()||!Vn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Cr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Ya.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Ve(r=!1){return _e.update(r?1:0).then(i=>i.audioInputs.devices)}function Fe(r=!1){return _e.update(r?2:0).then(i=>i.videoInputs.devices)}function yr(r=!1){return p(this,null,function*(){return _e.update(r?1:0).then(i=>i.audioOutputs.devices)})}var Ya=new Set;function Ou(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!!Ya.has(t)}function Du(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!!Ya.has(t)}function qa(r,i){return p(this,null,function*(){let t=(yield Ve()).find(s=>s.deviceId===Mi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function ku(n){return p(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Mi?yield qa(e,t):!0})}var zm=function(r){return p(this,null,function*(){let i=Ym(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Ve(),A.info(`microphones: ${dt(e,{keysToInclude:s})}`)),i.video&&(t=yield Fe(),A.info(`cameras: ${dt(t,{keysToInclude:s})}`));try{let n=yield navigator.mediaDevices.getUserMedia(i);return wa&&n.getTracks().forEach(o=>{A.info(`${o.kind} capabilities: ${dt(o.getCapabilities(),{keysToInclude:Ln})}`)}),n}catch(n){let{message:o}=n;throw n.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(o=O({key:v.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(o=O({key:v.MICROPHONE_NOT_FOUND}))),new N({code:S.INITIALIZE_FAILED,name:n.name,message:o,constraint:n.constraint})}})},Qm=Tt({retryFunction:zm,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let n=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(n===1?t[0].video&&(t[0].maxResolution=!1,t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):n===2?t[0].useDeviceIdOnly=!0:n===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&Mu(t[0].microphoneId,!1),t[0].cameraId&&Mu(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{te.logFailedEvent({eventType:Le.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{te.logSuccessEvent({eventType:Le.GET_USER_MEDIA_RETRY}),te.uploadEvent({log:`stat-${Le.GET_USER_MEDIA_RETRY}-success-${r}`})}});function Mu(r,i){return p(this,null,function*(){let t=(i?yield Fe():yield Ve()).find(s=>s.deviceId===r);t&&Q(t.getCapabilities)&&A.warn(dt(t.getCapabilities(),{keysToInclude:Ln}))})}function Ym(r){return{audio:qm(r),video:Zm(r)}}function qm(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!yt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),ue(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),ue(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),ue(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),yt(i)?!0:i)}function Zm(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!yt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!q&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!q&&(e.height.max=r.height)),q&&tt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),yt(e)?!0:e)}var Lu=Qm;function Zn(r){return F((i,e)=>function(...t){return p(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function eo(r){return F((i,e)=>function(...t){return p(this,null,function*(){return r.call(this,i.apply(this,t))})})}function F(r){return function(i,e,t){return t.value=r(t.value,e),t}}var Si=new WeakMap,Nt=new WeakMap;function bt(){return function(r,i,e){let t=e.value,s=({fn:n,args:o,context:a,resolve:c,reject:d})=>{n.apply(a,o).then(c,d)};return e.value=function(...n){return new Promise((a,c)=>{if(Si.has(this)){let d=Si.get(this),{length:l}=d;d.push({fn:t,args:n,context:this,resolve:a,reject:c}),l===0&&s({fn:t,args:n,context:this,resolve:a,reject:c})}else Si.set(this,[{fn:t,args:n,context:this,resolve:a,reject:c}]),s({fn:t,args:n,context:this,resolve:a,reject:c})}).finally(()=>{let a=Si.get(this);a&&(a.shift(),a[0]&&s(y({},a[0])))})},e}}function xu(r){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=Si.get(this);if(o){let a=o.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(m=>{n.find(_=>_===m)||(l=!1)}),l?(c.reject(new N({code:S.API_CALL_ABORTED,message:r})),!1):!0});Si.set(this,a)}return s.apply(this,n)},t}}function to(r){return function(i,e,t){let s=t.value;return t.value=function(...n){var a,c;let o=[];return(a=Si.get(this))==null||a.forEach(d=>o.push(d)),(c=Nt.get(this))==null||c.forEach(d=>d.forEach(l=>o.push(l))),o.forEach(d=>{d.reject(new N({code:S.API_CALL_ABORTED,message:r}))}),Si.delete(this),Nt.delete(this),s.apply(this,n)},t}}function Za(r){return function(i,e,t){let s=t.value,n=a=>ee(r)?a[r]:r(...a),o=({fn:a,args:c,context:d,resolve:l,reject:m})=>{a.apply(d,c).then(l,m).finally(()=>{if(Nt.has(d)&&Nt.get(d).has(n(c))){let _=Nt.get(d).get(n(c));_&&(_.shift(),_[0]&&o(y({},_[0])))}})};return t.value=function(...a){return new Promise((c,d)=>{if(Nt.has(this))if(Nt.get(this).has(n(a))){let l=Nt.get(this).get(n(a));if(l){let{length:m}=l;l.push({fn:s,args:a,context:this,resolve:c,reject:d}),m===0&&o({fn:s,args:a,context:this,resolve:c,reject:d})}}else Nt.get(this).set(n(a),[{fn:s,args:a,context:this,resolve:c,reject:d}]),o({fn:s,args:a,context:this,resolve:c,reject:d});else{let l=new Map;l.set(n(a),[{fn:s,args:a,context:this,resolve:c,reject:d}]),Nt.set(this,l),o({fn:s,args:a,context:this,resolve:c,reject:d})}})},t}}var He=class extends Hi{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"profile");this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return this.state==="publish"}installTrackEvent(e){Pe(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){pe(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){var t;try{let s=U();g.emit(f.LOCAL_TRACK_CAPTURE_START,{track:this});let n;e.customSource?(n=new MediaStream,n.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),n=yield Lu(e));let o=n.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),g.emit(f.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-s}),n}catch(s){throw g.emit(f.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){this.state===P.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}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),t}unpublish(){this.room&&this.room.localTracks.delete(this),g.emit(f.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&Rt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield ku({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),qn().then(o=>{let a=o.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&&!Du(this.mediaTrack)||this.kind===h.VIDEO&&!Ou(this.mediaTrack)||this._isRecapturing||e&&tt&&Ke)}onTrackMuted(){if(ya(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<mr){setTimeout(()=>this.onTrackMuted(),mr);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Be||ge)&&document.visibilityState!=="visible")return;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<mr){setTimeout(()=>this.onTrackEnded(),mr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let n;(this.kind==="audio"?yield Ve():yield Fe()).find(a=>a.deviceId===e)&&(n=e),t.deviceId=n}return this.capture(t).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 e=this instanceof ae;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(ws.get(t)||0)+1;if(ws.set(t,s),s>=3){let n=e?(yield Fe()).find(o=>!ws.has(o.deviceId)):(yield Ve()).find(o=>!ws.has(o.deviceId));n&&(this.log.warn(`${t} capture fail ${s} times, change new ${n.deviceId}`),t=n.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};b([oe(P.INIT,"capture",{ignoreError:!0,sync:!0})],He.prototype,"setStateToCapture",1),b([bt()],He.prototype,"capture",1),b([oe("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),g.emit(f.LOCAL_TRACK_PUBLISHED,{track: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===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],He.prototype,"publish",1),b([F(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"})})}),oe([],"capture",{sync:!0})],He.prototype,"unpublish",1);var ws=new Map;g.on(f.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&ws.delete(r.track.deviceId)});var ye=class extends He{constructor(e){super(1,Qn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");this.manager=e,this.pipeline=new Ar(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return p(this,null,function*(){yield Re(ye.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};B.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),B.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),B.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:n}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:n})}`),this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId: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,useExactDeviceId:s,customSource:t})}switchDevice(e){return p(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Mi){if(yield qa(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),g.emit(f.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(){_e&&!_e.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_e.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 Ve();t[0]?this.recapture(t[0].deviceId):_e.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(n){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let o=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,o=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,o=!0),!E(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,o=!0),o&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&B.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(Ut<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}B.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),_e.off("audioInputAdded",this.handleMicrophoneAdded,this),_e.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Re(ye.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Ve()).find(n=>n.deviceId!==e);if(s)yield Re(ye.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var ae=class extends He{constructor(e,t=4){super(t,ut);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");this.manager=e;let s=()=>{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(L(y({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Rt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}setMute(e){return p(this,null,function*(){var t,s,n;if(z(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Re(ae.prototype,this,"setMute").call(this,!1)}else yield(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,Re(ae.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:n}){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,useExactDeviceId:s,customSource:n})}setProfile(e){let t=y({},e),s=t.width>t.height;t.width*t.height<=160*120&&ge&&bi&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ea&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(L(y({},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 Rt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Na()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var 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*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),g.emit(f.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){_e&&!_e.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_e.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 Fe();t[0]?this.recapture(t[0].deviceId):_e.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}play(e,t){return p(this,null,function*(){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),Re(ae.prototype,this,"play").call(this,e,t)})}close(){_e.off("videoInputAdded",this.handleCameraAdded,this),_e.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Re(ae.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Fe()).find(n=>n.deviceId!==e);if(s)yield Re(ae.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var wu=Ss();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:wu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var sp=function(r){return p(this,null,function*(){let i=null,e=ap(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(cr&&Ut<74||Ke||q)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(n){A.warn(`screen applyConstraints failed: ${n}`)}r.captureElement&&(yield np(s,r.captureElement))}if(r.audio){let n=op(r);A.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),i=yield navigator.mediaDevices.getUserMedia(n),t.addTrack(i.getAudioTracks()[0])}return t})};function np(r,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Q(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===wu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function op(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return E(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function ap(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab",systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ke?{max:r.width}:{ideal:r.width,max:r.width},height:Ke?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:n=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:n,sampleRate:48e3}}return i}var Vu=sp;var Ge=class extends ae{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:n,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||o?(m=new MediaStream,a&&m.addTrack(a),o&&m.addTrack(o)):m=yield Vu({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:n,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof N?m:new N({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};var vt=class extends ye{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var cp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",ec;function Uu(r){return p(this,null,function*(){let i=we("dump");ec||(ec=gi(i,URL.createObjectURL(new Blob([cp],{type:"application/javascript"})))),yield ec;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var io=class extends Kn{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",A.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,m;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let n=new AbortController,o=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")},e*1e3),c=()=>{for(let _=0;_<s.length;_++){let T=URL.createObjectURL(new Blob(o[_])),C=document.createElement("a");C.href=T,C.download=`${s[_]}.pcm`,C.style.display="none",document.body.appendChild(C),C.click(),URL.revokeObjectURL(T),C.remove()}clearTimeout(a),n.abort("download")},d=Uu(t).then(_=>_.pipeTo(new WritableStream({write(T){T.forEach((C,R)=>o[R]=o[R]?o[R].concat(C[0]):[C[0]])}}),n).catch(T=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){var t;if(e instanceof vt)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof ye)this._localAudioTrack=e,this.destination.channelCount=((t=e.trackSettings)==null?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof Zt)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof vt?delete this._localScreenAudioTrack:e instanceof ye?delete this._localAudioTrack:e instanceof Zt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function ro(r=30,i=2){return F((e,t)=>function(...s){return new Promise((n,o)=>{let a=setTimeout(()=>{let c=new N({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?o(c):i===1&&n()},r*1e3);e.apply(this,s).then(n,o).finally(()=>{clearTimeout(a)})})})}var tc=class extends Hi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);this.tinyId=t.tinyId}setMute(e){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===tc.STATE_SUBSCRIBE}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)}},Ye=tc;u(Ye,"STATE_SUBSCRIBE","subscribe"),b([ro(5,1)],Ye.prototype,"waitHasMediaTrack",1),b([oe(P.INIT,Ye.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),g.emit(f.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],Ye.prototype,"subscribe",1),b([oe(Ye.STATE_SUBSCRIBE,P.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),g.emit(f.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ye.prototype,"unsubscribe",1);var Zt=class extends Ye{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager,this.player.on("code3",()=>{e.code3()})}write(e){this.player.write(e)}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}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 Ot=class extends Ye{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}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}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Nr=class extends Ot{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function fe(...r){}var dp=r=>r();function rc(){this.dispose()}var up=()=>typeof __FASTRX_DEVTOOLS__!="undefined",lp=1,ei=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ic(i,this,this.streamId++);return ht.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Vs=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=fe,this.error=fe,this.next=fe,this.dispose=fe,this.subscribe=fe,this.doDefer()}subscribe(i){return i instanceof ei?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(dp),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 Vs{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 Bu(r,...i){return i.reduce((e,t)=>t(e),r)}function ti(r,i,e){if(up()){let t=Object.defineProperties(Object.setPrototypeOf(r,ei.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}});ht.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof ei&&ht.addSource(t,n)}return t}return r}function G(r,i){return function(...e){return t=>{if(t instanceof ei){let s=ti(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,ht.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ii(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var ic=class extends w{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{ht.defer(this.source,this.id)})}next(i){ht.next(this.source,this.id,i),this.sink.next(i)}complete(){ht.complete(this.source,this.id),this.sink.complete()}error(i){ht.complete(this.source,this.id,i),this.sink.error(i)}},ht={addSource(r,i){Ii("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ii("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ii("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ii("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ii("defer",{id:r.id,streamId:i})},pipe(r){Ii("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ii("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=lp++),Ii("create",{name:r.toString(),id:r.id})}},so=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var sc=class extends Vs{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 no(){return r=>{let i=new sc(r);if(r instanceof ei){let e=ti(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,ht.pipe(e),e}return ti(i.add.bind(i),"share",arguments)}}function hp(...r){return ti(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new w(i);l.next=m=>{--t===0?(l.next=_=>{n[d]=_,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var nc=class extends w{constructor(i,...e){super(i);let t=new w(this.sink);t.next=s=>this.buffer=s,t.complete=fe,t.subscribe(hp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},uI=G(nc,"withLatestFrom"),oc=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()}},lI=G(oc,"bufferCount"),ac=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=fe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},hI=G(ac,"buffer");function cc(r){let i=arguments,e=no()(ti(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=fe,e.complete=fe,e.error=fe,e}function $u(r){return ti(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var dc=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=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},mp=G(dc,"reduce");var uc=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)}},pp=G(uc,"filter"),lc=class extends w{next(i){}},RI=G(lc,"ignoreElements"),hc=class extends w{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},_p=G(hc,"take"),mc=class extends w{constructor(i,e){super(i);let t=new w(i);t.next=()=>i.complete(),t.complete=rc,t.subscribe(e)}},CI=G(mc,"takeUntil"),pc=class extends w{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},fp=G(pc,"takeWhile");var _c=class extends w{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},yI=G(_c,"skip"),fc=class extends w{constructor(i,e){super(i),i.next=fe;let t=new w(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=rc,t.subscribe(e)}},NI=G(fc,"skipUntil"),Ec=class extends w{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Ep=G(Ec,"skipWhile"),Tp={leading:!0,trailing:!1},Tc=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)}},gc=class extends w{constructor(i,e,t=Tp){super(i),this.durationSelector=e,this.config=t,this._throttle=new Tc(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=fe,this._throttle.complete(),super.complete()}},bI=G(gc,"throttle");var Sc=class extends w{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ic=class extends w{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Sc(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()}},vI=G(Ic,"debounce");var Ac=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()}},OI=G(Ac,"elementAt");var Rc=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}},DI=G(Rc,"findIndex"),Cc=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()}},kI=G(Cc,"first"),yc=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()}},MI=G(yc,"last"),Nc=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()}},LI=G(Nc,"every");var bc=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))}},VI=G(bc,"scan"),vc=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}},UI=G(vc,"pairwise"),Oc=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))}},Hu=G(Oc,"map");var br=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()}},vr=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()}},oo=class extends br{},ao=class extends vr{next(i){this.subInner(i,oo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,oo)}}},gp=G(ao,"switchMap");function ho(r){return(i,e)=>r(()=>i,e)}var BI=ho(G(ao,"switchMapTo")),Dc=class extends br{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},co=class extends vr{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(),Dc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},$I=G(co,"concatMap"),HI=ho(G(co,"concatMapTo")),kc=class extends br{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},uo=class extends vr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,kc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},FI=G(uo,"mergeMap"),GI=ho(G(uo,"mergeMapTo")),Mc=class extends br{dispose(){this.context.resetNext(),super.dispose()}},lo=class extends vr{next(i){this.next=fe,this.subInner(i,Mc)}},WI=G(lo,"exhaustMap"),JI=ho(G(lo,"exhaustMapTo")),Lc=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=cc(),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)}},jI=G(Lc,"groupBy"),xc=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}},KI=G(xc,"timeInterval"),Pc=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()}},XI=G(Pc,"bufferTime"),wc=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)}},zI=G(wc,"delay"),Vc=class extends w{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},QI=G(Vc,"catchError");var Uc=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)}))}},eA=G(Uc,"tap"),Bc=class extends w{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new so(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},tA=G(Bc,"timeout");var TA=Bu($u(250),Hu(()=>performance.now()),no());var Or=new Map;g.on(f.JOIN_SUCCESS,({room:r})=>{Te(r.userId,{eventId:32788,eventDesc:"join room"})});g.on(f.LEAVE_START,({room:r})=>{Te(r.userId,{eventId:32789,eventDesc:"leave room"})});g.on(f.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),Te(r.room.userId,{eventId:i,eventDesc:`publish ${r.kind}`})}});g.on(f.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),Te(r.room.userId,{eventId:i,eventDesc:`unpublish ${r.kind}`})}});g.on(f.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?Te(r.room.userId,{eventId:r.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:r.isRemote?r.userId:void 0}):Te(r.room.userId,{eventId:r.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:r.isRemote?r.userId:void 0}))});g.on(f.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?Te(r.room.userId,{eventId:r.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:r.isRemote?r.userId:void 0}):Te(r.room.userId,{eventId:r.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:r.isRemote?r.userId:void 0}))});g.on(f.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&Te(r.room.userId,{eventId:32777,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&Te(r.room.userId,{eventId:32776,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&Te(r.room.userId,{eventId:32803,eventDesc:`${h.SUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});g.on(f.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&Te(r.room.userId,{eventId:32779,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&Te(r.room.userId,{eventId:32778,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&Te(r.room.userId,{eventId:32804,eventDesc:`${h.UNSUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});g.on(f.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&Te(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781,eventDesc:`switch ${r.kind===h.VIDEO?"camera":"microphone"}`})});g.on(f.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&Te(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783,eventDesc:`replace ${r.kind}`})});g.on(f.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&&Te(r.userId,{eventId:t,eventDesc:s})});g.on(f.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n=s?"downlink":"uplink",o,a;switch(e){case"CONNECTED":i==="RECONNECTING"?(o=s?32801:32798,a=`${n} reconnected`):(o=s?32793:32792,a=`${n} connected`);break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799,a=`${n} reconnect fail`);break;case"RECONNECTING":o=s?32800:32797,a=`${n} reconnecting`;break}o&&a&&Te(r.userId,{eventId:o,eventDesc:a,remoteUserId:t})});function Te(r,i){let e=L(y({},i),{timestamp:Wr()});Or.has(r)?Or.get(r).push(e):Or.set(r,[e])}function Fu(r){if(Or.has(r)){let i=Or.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return Or.delete(r),i}return[]}var Gu=ve(Ue(),1);var mo=class extends Gu.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===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 n=`peer leave [${e}]`;E(t)||(n+=`:${pa[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.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(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=Ei(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Ei(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Wu({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return F((t,s)=>{let n=new Map;return g.on(f.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.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(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new N({code:S.INVALID_OPERATION,message:O({key:v.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...o)}})}var Ju=!0,ju=function(){var r;Ju&&(Ju=!1,A.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${_t}/en/index.html`),console.info(`* Changelog: ${_t}/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":""}`),is().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 Dt={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 x={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},kt=(I=>(I[I.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",I[I.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",I[I.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",I[I.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",I[I.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",I[I.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",I[I.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",I[I.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",I[I.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",I[I.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",I[I.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",I[I.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",I[I.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",I[I.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",I[I.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",I[I.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",I[I.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",I[I.INVALID_OPERATION=5100]="INVALID_OPERATION",I[I.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",I[I.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",I[I.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",I[I.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",I[I.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",I[I.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",I[I.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",I[I.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",I[I.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",I[I.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",I[I.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",I[I.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",I[I.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",I[I.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",I[I.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",I[I.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",I[I.DEVICE_ERROR=5300]="DEVICE_ERROR",I[I.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",I[I.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",I[I.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",I[I.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",I[I.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",I[I.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",I[I.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",I[I.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",I[I.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",I[I.SERVER_ERROR=5400]="SERVER_ERROR",I[I.NEED_TO_BUY=5401]="NEED_TO_BUY",I[I.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",I[I.OPERATION_FAILED=5500]="OPERATION_FAILED",I[I.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",I[I.REJOIN_FAILED=5502]="REJOIN_FAILED",I[I.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",I[I.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",I[I.OPERATION_ABORT=5998]="OPERATION_ABORT",I[I.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",I))(kt||{});function Xu({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=kt[r];try{s=Ku[n]}catch(o){s=Ku.UNKNOWN_ERROR}return Q(s)?t=s(i):z(s)&&(t=s),e&&(t+=" doc:"),t}var Ku=L(y({},Ee),{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}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${me(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}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${me(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}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",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}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},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.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=Fi(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=Fi(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=Fi(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=Fi(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=Fi(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=Fi(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=Fi(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.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},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 Fi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Gi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=Xu({code:t||e,params:y({fnName:o,error:a},n)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=kt[e],this.code=e,this.extraCode=t,this.functionName=o,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");wt?_.href=`ms-settings:privacy-${m[this.functionName]}`:tt&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof N){let{stack:o}=e,a={code:x.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=x.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=x.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=x.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ee.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=x.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=x.OPERATION_ABORT;break;case S.DEVICE_NOT_FOUND:case S.DEVICE_AUTO_RECOVER_FAILED:case S.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=Sp(e.name));break;case S.UNKNOWN:break;default:a.code=x.OPERATION_FAILED}n=new Gi(a),o&&(n.stack+=o.substr(o.indexOf(`
|
|
103
|
-
`)))}else{if(e instanceof Gi)return e;n=new Gi({code:x.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function Sp(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 k=Gi;var zu={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Qu={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}}},Dr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:x.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Yu={name:"userId",required:!0,type:"string"},qu={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Dt.AUDIO_PROFILE_STANDARD,Dt.AUDIO_PROFILE_STANDARD_STEREO,Dt.AUDIO_PROFILE_HIGH,Dt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function _o(r,i){if(!r)throw new k({code:x.INVALID_OPERATION,extraCode:5101,fnName:i})}function Zu(r,i,e){if(!r)throw new k({code:x.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var dC={type:"number",notLessThanZero:!0},Ip={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 k({code:x.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:x.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:x.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 k({code:x.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:x.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:Dr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:zu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Xt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(y({},Dr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:zu}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:qu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Xt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:qu}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Dr,publish:{type:"boolean"},option:Qu},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&Xt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201});if(!As())throw new k({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Dr,publish:{type:"boolean"},option:Qu}},muteRemoteAudio:[Yu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Yu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Dr,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){_o(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(Zu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:x.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(y({},Dr),{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){_o(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(Zu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:x.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!=="*"&&E(r.streamType))throw new k({code:x.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){_o(this._room.isJoining||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(!Vi)throw new k({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:x.INVALID_OPERATION,messageParams:{key:v.SEI_DISABLED}});if(r.byteLength>1e3)throw new k({code:x.INVALID_PARAMETER,messageParams:{key:v.SEI_OVERSIZE,data:r.byteLength}});if(r.byteLength===0)throw new k({code:x.INVALID_PARAMETER,messageParams:{key:v.SEI_EMPTY}});if(_o(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new k({code:x.INVALID_PARAMETER,messageParams:{key:v.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},Ie={TRTC:Ip};var Ne=class extends Error{};function Ap(r,i){let e=fr(r);for(let t=0;t<i.length;t++)Wt(e[t],i[t]);return e}function Rp(r){this._resolve=Promise.resolve(r)}function Cp(r){this._reject=Promise.reject(r)}var kr=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=Ap;let t=kr.instances.get(i);t?t.set(e,this):kr.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=kr.instances.get(i);return t&&t.get(e)||new kr(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},n=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Ne("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:Rp,reject:Cp};try{switch(this.state){case 1:if(i===0)throw new Ne("already started");break;case 4:if(i===2)throw new Ne("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Ne("already start");break;case 3:switch(i.type){case 2:throw new Ne("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ne("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Ne("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 Ne("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ne("start not allowed after update");case 0:throw new Ne("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Ne("keep start")),new Ne("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}},ii=kr;ii.instances=new WeakMap;var fo=new WeakMap,Eo=(r,i)=>{if(i instanceof Ne){let{stack:e}=i;i=new k({code:x.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
104
|
-
`)))}throw i};function Ai(r,i){return F((e,t)=>function(...s){let n=ii.get(this,typeof r=="string"?r:r.call(this,...s));return i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(Eo.bind(null,t))})}function Wi(r,i){let{merge:e,debounce:t}=i||{};return F((s,n)=>function(...o){let a=ii.get(this,typeof r=="string"?r:r.call(this,...o));if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,o)){let{delay:c,getKey:d}=t;return new Promise((l,m)=>{var C,R;let _=(C=fo.get(this))==null?void 0:C.get(d(...o));if(_){let{timeoutId:M,resolve:re}=_;clearTimeout(M),re()}let T=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(Eo.bind(null,n)).then(l,m)},c);fo.has(this)?(R=fo.get(this))==null||R.set(d(...o),{timeoutId:T,resolve:l}):fo.set(this,new Map([[d(...o),{timeoutId:T,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(Eo.bind(null,n))})}function Ri(r){return F((i,e)=>function(...t){return ii.get(this,typeof r=="string"?r:r.call(this,...t)).action(3,i.bind(this),t).catch(Eo.bind(null,e))})}var $={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",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",TRACK:"track"};function Us(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Bs(r){return r===Dt.QOS_PREFERENCE_CLEAR?"detail":r===Dt.QOS_PREFERENCE_SMOOTH?"motion":""}function il(r,i,e){return{room:r,assetsPath:e,innerEmitter:g,constants:_a,environment:ci,utils:De,eventLogger:te,log:r.getLogger(),errorModule:i,kvStatManager:B,clearStarted(t,s){let n=t.getAlias(),o=ii.instances.get(r);if(!!o)if(s){let a=o.get(n+s);if(!a)return;a.started=!1}else o.forEach((a,c)=>{c.startsWith(n)&&(a.started=!1)})}}}var rl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=O({key:v.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${n}
|
|
31
|
+
`,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=Ha,s.innerText=`${ft()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let n=i.content.firstChild,o=n.querySelector(`.${Hn}`);return o.appendChild(s),o.appendChild(t),o.appendChild(e),n}addDiaLog(){Wa()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Er}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),ee.uploadEvent({log:Lm}))}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"),T.emit(f.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${fu}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ee.uploadEvent({log:xm}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Su,"_blank"),this._isQuestionClicked||ee.uploadEvent({log:Pm}),this._isQuestionClicked=!0}},Iu=Fa;var dt=class extends Xt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}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){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!Wa()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let n=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}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)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(){var e;super.stop(),(e=this.canvas)==null||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(xe.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function gi(r,i){return p(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),A.info("worklet addModule success")}catch(e){throw A.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Pi=new window.AudioContext({sampleRate:48e3}),Gn=()=>{Pi.state==="suspended"?(Pi.resume(),document.addEventListener("click",Gn)):Pi.state==="interrupted"?Pi.resume():document.removeEventListener("click",Gn)};document.addEventListener("click",Gn);Pi.onstatechange=()=>{A.info(`context state: ${Pi.state}`),Gn()};var $e=r=>Pi;var Vm=1,Um=0,Wn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=A.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?Jn.START_MICROPHONE:Ja.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?Jn.START_MICROPHONE:Ja.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:ba(this.version||Te),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,n])=>({uint32_item_key:s,uint32_item_value:n}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var n;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((n=this.distributionMap)==null?void 0:n.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,o=0;if(re(t))o=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){o=c;break}n.set(o,(n.get(o)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Vm,useUV:!1}),e)){let n=+String(i).slice(-3);n<800&&n>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;re(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code),this.addEnum({key:i,value:Um,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},ja=(W=>(W[W.enterRoom=500700]="enterRoom",W[W.exitRoom=500701]="exitRoom",W[W.switchRole=500702]="switchRole",W[W.destroy=500703]="destroy",W[W.startLocalAudio=500704]="startLocalAudio",W[W.updateLocalAudio=500705]="updateLocalAudio",W[W.stopLocalAudio=500706]="stopLocalAudio",W[W.startLocalVideo=500707]="startLocalVideo",W[W.updateLocalVideo=500708]="updateLocalVideo",W[W.stopLocalVideo=500709]="stopLocalVideo",W[W.startScreenShare=500710]="startScreenShare",W[W.updateScreenShare=500711]="updateScreenShare",W[W.stopScreenShare=500712]="stopScreenShare",W[W.startRemoteVideo=500713]="startRemoteVideo",W[W.updateRemoteVideo=500714]="updateRemoteVideo",W[W.stopRemoteVideo=500715]="stopRemoteVideo",W[W.muteRemoteAudio=500716]="muteRemoteAudio",W[W.setRemoteAudioVolume=500717]="setRemoteAudioVolume",W))(ja||{}),Ka=(n=>(n[n.AudioMixer=550700]="AudioMixer",n[n.AIDenoiser=551700]="AIDenoiser",n[n.VirtualBackground=570700]="VirtualBackground",n[n.Beauty=571700]="Beauty",n[n.Watermark=572700]="Watermark",n))(Ka||{}),Xa=(n=>(n[n.AudioMixer=550701]="AudioMixer",n[n.AIDenoiser=551701]="AIDenoiser",n[n.VirtualBackground=570701]="VirtualBackground",n[n.Beauty=571701]="Beauty",n[n.Watermark=572701]="Watermark",n))(Xa||{}),Qa=(n=>(n[n.AudioMixer=550702]="AudioMixer",n[n.AIDenoiser=551702]="AIDenoiser",n[n.VirtualBackground=570702]="VirtualBackground",n[n.Beauty=571702]="Beauty",n[n.Watermark=572702]="Watermark",n))(Qa||{}),Jn=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(Jn||{});var Ja=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(Ja||{});var Bm=new Wn(!0),wi=new Wn(!1);var P=Bm;var zt=class{constructor(){this.pre=new Set;this.next=new Set;this.connectedNodes=new Set}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.preNodeReconnect(),this.reconnect(),P.addSuccessEvent({key:502701})}catch(t){A.error(t),P.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),P.addSuccessEvent({key:502702})}catch(e){A.error(e),P.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},jn=class extends zt{constructor(e=256){super();this.fftSize=e;this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,s=0,n=0,o=`M${s},${n}`;for(let a=0;a<e.length;a++)n=e[a]/128*100/2,o+=`L${s},${n}`,s+=t;return o}},Os=class{constructor(){this.source=new zt;this.gain=new zt;this.destination=new zt}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode($m(i))}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},gr=class extends Os{constructor(e){super();this.context=e;this.denoiser=new zt;this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},Kn=class{constructor(){this.audioContext=$e("audio-mixer");this.destination=this.audioContext.createMediaStreamDestination();this.inputs=new Set;this.mixWeight=0;this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Au=new WeakMap;function $m(r){let i=Au.get(r);if(i)return i;let e=$e();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return Au.set(r,i),i}var Hm='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);',Vi=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Vi.workletReady||(Vi.workletReady=gi(Vi.audioContext,URL.createObjectURL(new Blob([Hm],{type:"application/javascript"})))),Vi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Vi.audioContext,"volume-meter"),this._audioWorkletNode.port.onmessage=i=>{this._volume=i.data.volume||0},this.handleAudioLevelInterval({interval:this._interval})}catch(i){ee.logFailedEvent({userId:this._log.userId,eventType:Me.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=$e("volume-meter").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}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}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})}},Ds=Vi;u(Ds,"audioContext",$e("volume-meter")),u(Ds,"workletReady");var Xn=class extends zt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ds(e)}deleteNode(){this._volumeMeter.destroy(),super.deleteNode()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}};var za=class extends Os{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"analyser",new jn);this.volumeMeter=new Xn({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},Tr=class extends Xt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",$e("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new za(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((_t==="15.2"||_t==="15.3"||_t==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,this.bindElementEvents()}play(){return p(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode($e("player").createAnalyser()),this.setVolume(this._volume),Ae(Tr.prototype,this,"play").call(this)})}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return p(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Qn=class extends Tr{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(xe.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},zn=class extends Tr{constructor(e){super(e);u(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(xe.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),pe(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}};var Ui=class extends w{constructor({userId:e,sdkAppId:t,mediaType:s,room:n,PlayerClass:o=s===1?zn:dt}){var a;super();u(this,"id",Es());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=n||this.room)==null?void 0:a.userId,remoteUserId:this instanceof He?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof He}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this.log}),this.player.on(xe.PLAYER_STATE_CHANGED,c=>{T.emit(f.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(xe.LOADED_DATA,()=>{T.emit(f.VIDEO_LOADED_DATA,{track:this})}),this.player.on(xe.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.setTrack(c))}))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}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&&!E(t.muted)&&this.setPlayerMute(t.muted),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof dt&&(this.player.setObjectFit(this.objectFit),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&&!E(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof dt&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof dt&&this.player.setContainer(s)),T.emit(f.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.playerMediaTrack),yield this.player.play(),de(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let s=this.player;if(t&&(s=t),ue(this.mirror)){s.setViewMirror(this.mirror),this.room&&(this.room.videoManager.mirror=!1);return}switch(this.mirror){case"view":{this.room&&(this.room.videoManager.mirror=!1),s.setViewMirror(!0);break}case"publish":{this.room&&(this.room.videoManager.mirror=!0),s.setViewMirror(!0);break}case"both":this.room&&(this.room.videoManager.mirror=!0),s.setViewMirror(!1)}}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((n,o)=>{var a;e.find(c=>o===c)||(n.stop(),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[n,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new dt({id:this.userId||this.id,track:this.playerMediaTrack,container:o,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${n+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let n of s)n.setViewMirror(this.player.mirror),yield n.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),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){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),T.emit(e?f.TRACK_MUTED:f.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):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,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>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 Iu;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)}}getVideoFrame(){return this.player instanceof dt?this.player.getVideoFrame():""}};b([oe([],w.INIT,{sync:!0})],Ui.prototype,"close",1);var Fm=Object.prototype.hasOwnProperty,{toString:vg}=Object.prototype;function Gm(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(Be(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(Fm.call(r,i))return!1;return!0}}return!1}var Ct=Gm;var yu=ve(Ve(),1);var Cu=r=>i=>i.deviceId===r;var Ms=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Sr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Cu(s.deviceId))){let n=`${this.kind}${this.type}Added`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Cu(s.deviceId))){let n=`${this.kind}${this.type}Removed`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},qa=class extends yu.EventEmitter{constructor(){super();u(this,"audioInputs",new Ms(h.AUDIO));u(this,"videoInputs",new Ms(h.VIDEO));u(this,"audioOutputs",new Ms(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Oi,()=>{this.update()},{delay:1e4}))}init(){qn().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield qn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},_e=Gr||Qi?null:new qa;function Sr(r){return r.deviceId===r.groupId&&r.groupId===""}function qn(){return p(this,arguments,function*(r=0){if(Jt()||!Vn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Sr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Ya.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function we(r=!1){return _e.update(r?1:0).then(i=>i.audioInputs.devices)}function Fe(r=!1){return _e.update(r?2:0).then(i=>i.videoInputs.devices)}function Ir(r=!1){return p(this,null,function*(){return _e.update(r?1:0).then(i=>i.audioOutputs.devices)})}var Ya=new Set;function Nu(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!!Ya.has(t)}function bu(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!!Ya.has(t)}function Za(r,i){return p(this,null,function*(){let t=(yield we()).find(s=>s.deviceId===vi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function vu(n){return p(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===vi?yield Za(e,t):!0})}var Wm=function(r){return p(this,null,function*(){let i=jm(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield we(),A.info(`microphones: ${ct(e,{keysToInclude:s})}`)),i.video&&(t=yield Fe(),A.info(`cameras: ${ct(t,{keysToInclude:s})}`));try{let n=yield navigator.mediaDevices.getUserMedia(i);return wa&&n.getTracks().forEach(o=>{A.info(`${o.kind} capabilities: ${ct(o.getCapabilities(),{keysToInclude:pn})}`)}),n}catch(n){let{message:o}=n;throw n.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(o=D({key:v.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(o=D({key:v.MICROPHONE_NOT_FOUND}))),new C({code:S.INITIALIZE_FAILED,name:n.name,message:o,constraint:n.constraint})}})},Jm=Et({retryFunction:Wm,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let n=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(n===1?t[0].video&&(t[0].maxResolution=!1,t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):n===2?t[0].useDeviceIdOnly=!0:n===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&Ou(t[0].microphoneId,!1),t[0].cameraId&&Ou(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{ee.logFailedEvent({eventType:Me.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{ee.logSuccessEvent({eventType:Me.GET_USER_MEDIA_RETRY}),ee.uploadEvent({log:`stat-${Me.GET_USER_MEDIA_RETRY}-success-${r}`})}});function Ou(r,i){return p(this,null,function*(){let t=(i?yield Fe():yield we()).find(s=>s.deviceId===r);t&&Q(t.getCapabilities)&&A.warn(ct(t.getCapabilities(),{keysToInclude:pn}))})}function jm(r){return{audio:Km(r),video:Xm(r)}}function Km(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Ct(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(re(r.channelCount)&&(i.channelCount=r.channelCount),ue(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),ue(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),ue(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Ct(i)?!0:i)}function Xm(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Ct(e)?e:(r.width&&(e.width={ideal:r.width},i&&!Y&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!Y&&(e.height.max=r.height)),Y&&pt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Ct(e)?!0:e)}var Du=Jm;function Yn(r){return F((i,e)=>function(...t){return p(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function Zn(r){return F((i,e)=>function(...t){return p(this,null,function*(){return r.call(this,i.apply(this,t))})})}function F(r){return function(i,e,t){return t.value=r(t.value,e),t}}var ku=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Qm=0,eo=class{constructor(){this.log=A.createLogger({id:`fq${++Qm}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var n,o;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(o=(n=this.lastQueueItem)==null?void 0:n.promise)==null||o.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:n}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Ls=new WeakMap,to=new WeakMap;function yt(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=Ls.get(this)||new eo;return Ls.set(this,o),o.push({fn:s,args:n,context:this},r)},t}}function Mu(r){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=Ls.get(this);if(o){let a=o.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(m=>{n.find(_=>_===m)||(l=!1)}),l?(c.reject(new C({code:S.API_CALL_ABORTED,message:r})),!1):!0});o.queue=a}return s.apply(this,n)},t}}function io(r){return function(i,e,t){let s=t.value;return t.value=function(...n){var a,c,d;let o=[];return(c=(a=Ls.get(this))==null?void 0:a.queue)==null||c.forEach(l=>o.push(l)),(d=to.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(m=>o.push(m))),o.forEach(l=>{l.reject(new C({code:S.API_CALL_ABORTED,message:r}))}),Ls.delete(this),to.delete(this),s.apply(this,n)},t}}function Ar(r){return function(i,e,t){let s=t.value,n=o=>r(...o);return t.value=function(...o){let a=to.get(this)||new Map,c=a.get(n(o))||new eo;return a.set(n(o),c),to.set(this,a),c.push({fn:s,args:o,context:this})},t}}var He=class extends Ui{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"profile");this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return this.state==="publish"}installTrackEvent(e){Pe(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){pe(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){var t;try{let s=B();T.emit(f.LOCAL_TRACK_CAPTURE_START,{track:this});let n;e.customSource?(n=new MediaStream,n.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),n=yield Du(e));let o=n.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(f.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:B()-s}),n}catch(s){throw T.emit(f.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){this.state===w.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}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),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(f.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&At){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield vu({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),qn().then(o=>{let a=o.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&&!bu(this.mediaTrack)||this.kind===h.VIDEO&&!Nu(this.mediaTrack)||this._isRecapturing||e&&pt&&Xe)}onTrackMuted(){if(ku(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Yi){setTimeout(()=>this.onTrackMuted(),Yi);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ue||Ce)&&document.visibilityState!=="visible")return;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<Yi){setTimeout(()=>this.onTrackEnded(),Yi);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let n;(this.kind==="audio"?yield we():yield Fe()).find(a=>a.deviceId===e)&&(n=e),t.deviceId=n}return this.capture(t).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 e=this instanceof ae;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(xs.get(t)||0)+1;if(xs.set(t,s),s>=3){let n=e?(yield Fe()).find(o=>!xs.has(o.deviceId)):(yield we()).find(o=>!xs.has(o.deviceId));n&&(this.log.warn(`${t} capture fail ${s} times, change new ${n.deviceId}`),t=n.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};b([oe(w.INIT,"capture",{ignoreError:!0,sync:!0})],He.prototype,"setStateToCapture",1),b([yt()],He.prototype,"capture",1),b([oe("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(f.LOCAL_TRACK_PUBLISHED,{track: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===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],He.prototype,"publish",1),b([F(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"})})}),oe([],"capture",{sync:!0})],He.prototype,"unpublish",1);var xs=new Map;T.on(f.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&xs.delete(r.track.deviceId)});var ye=class extends He{constructor(e){super(1,Qn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");this.manager=e,this.pipeline=new gr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return p(this,null,function*(){yield Ae(ye.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};P.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),P.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),P.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:n}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:n})}`),this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId: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,useExactDeviceId:s,customSource:t})}switchDevice(e){return p(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===vi){if(yield Za(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),T.emit(f.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(){_e&&!_e.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_e.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 we();t[0]?this.recapture(t[0].deviceId):_e.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(n){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let o=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,o=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,o=!0),!E(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,o=!0),o&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&P.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(Bt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}P.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),_e.off("audioInputAdded",this.handleMicrophoneAdded,this),_e.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Ae(ye.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield we()).find(n=>n.deviceId!==e);if(s)yield Ae(ye.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var ae=class extends He{constructor(e,t=4){super(t,dt);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");this.manager=e;let s=()=>{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",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!At||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}setMute(e){return p(this,null,function*(){var t,s,n;if(z(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ae(ae.prototype,this,"setMute").call(this,!1)}else yield(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,Ae(ae.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:n}){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,useExactDeviceId:s,customSource:n})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&Ce&&ki&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Ea&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(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 At&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Na()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var 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*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(f.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){_e&&!_e.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_e.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 Fe();t[0]?this.recapture(t[0].deviceId):_e.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}play(e,t){return p(this,null,function*(){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ae(ae.prototype,this,"play").call(this,e,t)})}close(){_e.off("videoInputAdded",this.handleCameraAdded,this),_e.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Ae(ae.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Fe()).find(n=>n.deviceId!==e);if(s)yield Ae(ae.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var xu=Es();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:xu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var ep=function(r){return p(this,null,function*(){let i=null,e=rp(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(ar&&Bt<74||Xe||Y)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(n){A.warn(`screen applyConstraints failed: ${n}`)}r.captureElement&&(yield tp(s,r.captureElement))}if(r.audio){let n=ip(r);A.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),i=yield navigator.mediaDevices.getUserMedia(n),t.addTrack(i.getAudioTracks()[0])}return t})};function tp(r,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Q(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===xu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function ip(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return E(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function rp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab",systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Xe?{max:r.width}:{ideal:r.width,max:r.width},height:Xe?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:n=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:n,sampleRate:48e3}}return i}var Pu=ep;var Ge=class extends ae{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:n,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||o?(m=new MediaStream,a&&m.addTrack(a),o&&m.addTrack(o)):m=yield Pu({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:n,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof C?m:new C({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};var Nt=class extends ye{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var sp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",ec;function wu(r){return p(this,null,function*(){let i=$e("dump");ec||(ec=gi(i,URL.createObjectURL(new Blob([sp],{type:"application/javascript"})))),yield ec;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var ro=class extends Kn{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",A.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,m;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let n=new AbortController,o=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")},e*1e3),c=()=>{for(let _=0;_<s.length;_++){let g=URL.createObjectURL(new Blob(o[_])),R=document.createElement("a");R.href=g,R.download=`${s[_]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(g),R.remove()}clearTimeout(a),n.abort("download")},d=wu(t).then(_=>_.pipeTo(new WritableStream({write(g){g.forEach((R,y)=>o[y]=o[y]?o[y].concat(R[0]):[R[0]])}}),n).catch(g=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){var t;if(e instanceof Nt)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof ye)this._localAudioTrack=e,this.destination.channelCount=((t=e.trackSettings)==null?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof qt)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Nt?delete this._localScreenAudioTrack:e instanceof ye?delete this._localAudioTrack:e instanceof qt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function so(r=30,i=2){return F((e,t)=>function(...s){return new Promise((n,o)=>{let a=setTimeout(()=>{let c=new C({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?o(c):i===1&&n()},r*1e3);e.apply(this,s).then(n,o).finally(()=>{clearTimeout(a)})})})}var tc=class extends Ui{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);this.tinyId=t.tinyId}setMute(e){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===tc.STATE_SUBSCRIBE}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)}},qe=tc;u(qe,"STATE_SUBSCRIBE","subscribe"),b([so(5,1)],qe.prototype,"waitHasMediaTrack",1),b([oe(w.INIT,qe.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(f.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],qe.prototype,"subscribe",1),b([oe(qe.STATE_SUBSCRIBE,w.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(f.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],qe.prototype,"unsubscribe",1);var qt=class extends qe{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}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 bt=class extends qe{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}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}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Rr=class extends bt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function fe(...r){}var np=r=>r();function rc(){this.dispose()}var op=()=>typeof __FASTRX_DEVTOOLS__!="undefined",ap=1,Yt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ic(i,this,this.streamId++);return ut.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Ps=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=fe,this.error=fe,this.next=fe,this.dispose=fe,this.subscribe=fe,this.doDefer()}subscribe(i){return i instanceof Yt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(np),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}},V=class extends Ps{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 Vu(r,...i){return i.reduce((e,t)=>t(e),r)}function Zt(r,i,e){if(op()){let t=Object.defineProperties(Object.setPrototypeOf(r,Yt.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}});ut.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof Yt&&ut.addSource(t,n)}return t}return r}function G(r,i){return function(...e){return t=>{if(t instanceof Yt){let s=Zt(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,ut.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ti(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var ic=class extends V{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{ut.defer(this.source,this.id)})}next(i){ut.next(this.source,this.id,i),this.sink.next(i)}complete(){ut.complete(this.source,this.id),this.sink.complete()}error(i){ut.complete(this.source,this.id,i),this.sink.error(i)}},ut={addSource(r,i){Ti("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ti("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ti("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ti("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ti("defer",{id:r.id,streamId:i})},pipe(r){Ti("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ti("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=ap++),Ti("create",{name:r.toString(),id:r.id})}},no=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var sc=class extends Ps{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 oo(){return r=>{let i=new sc(r);if(r instanceof Yt){let e=Zt(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,ut.pipe(e),e}return Zt(i.add.bind(i),"share",arguments)}}function cp(...r){return Zt(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new V(i);l.next=m=>{--t===0?(l.next=_=>{n[d]=_,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var nc=class extends V{constructor(i,...e){super(i);let t=new V(this.sink);t.next=s=>this.buffer=s,t.complete=fe,t.subscribe(cp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},nI=G(nc,"withLatestFrom"),oc=class extends V{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()}},oI=G(oc,"bufferCount"),ac=class extends V{constructor(i,e){super(i),this.buffer=[];let t=new V(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=fe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},aI=G(ac,"buffer");function cc(r){let i=arguments,e=oo()(Zt(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=fe,e.complete=fe,e.error=fe,e}function Uu(r){return Zt(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var dc=class extends V{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},dp=G(dc,"reduce");var uc=class extends V{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},up=G(uc,"filter"),lc=class extends V{next(i){}},gI=G(lc,"ignoreElements"),hc=class extends V{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},lp=G(hc,"take"),mc=class extends V{constructor(i,e){super(i);let t=new V(i);t.next=()=>i.complete(),t.complete=rc,t.subscribe(e)}},TI=G(mc,"takeUntil"),pc=class extends V{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},hp=G(pc,"takeWhile");var _c=class extends V{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},SI=G(_c,"skip"),fc=class extends V{constructor(i,e){super(i),i.next=fe;let t=new V(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=rc,t.subscribe(e)}},II=G(fc,"skipUntil"),Ec=class extends V{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},mp=G(Ec,"skipWhile"),pp={leading:!0,trailing:!1},gc=class extends V{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)}},Tc=class extends V{constructor(i,e,t=pp){super(i),this.durationSelector=e,this.config=t,this._throttle=new gc(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=fe,this._throttle.complete(),super.complete()}},AI=G(Tc,"throttle");var Sc=class extends V{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ic=class extends V{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Sc(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()}},RI=G(Ic,"debounce");var Ac=class extends V{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()}},CI=G(Ac,"elementAt");var Rc=class extends V{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}},yI=G(Rc,"findIndex"),Cc=class extends V{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()}},NI=G(Cc,"first"),yc=class extends V{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()}},bI=G(yc,"last"),Nc=class extends V{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()}},vI=G(Nc,"every");var bc=class extends V{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))}},MI=G(bc,"scan"),vc=class extends V{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},LI=G(vc,"pairwise"),Oc=class extends V{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Bu=G(Oc,"map");var Cr=class extends V{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()}},yr=class extends V{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()}},ao=class extends Cr{},co=class extends yr{next(i){this.subInner(i,ao),this.next=e=>{this.currentSink.dispose(),this.subInner(e,ao)}}},_p=G(co,"switchMap");function mo(r){return(i,e)=>r(()=>i,e)}var xI=mo(G(co,"switchMapTo")),Dc=class extends Cr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},uo=class extends yr{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(),Dc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},PI=G(uo,"concatMap"),wI=mo(G(uo,"concatMapTo")),kc=class extends Cr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},lo=class extends yr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,kc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},VI=G(lo,"mergeMap"),UI=mo(G(lo,"mergeMapTo")),Mc=class extends Cr{dispose(){this.context.resetNext(),super.dispose()}},ho=class extends yr{next(i){this.next=fe,this.subInner(i,Mc)}},BI=G(ho,"exhaustMap"),$I=mo(G(ho,"exhaustMapTo")),Lc=class extends V{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=cc(),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)}},HI=G(Lc,"groupBy"),xc=class extends V{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}},FI=G(xc,"timeInterval"),Pc=class extends V{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()}},GI=G(Pc,"bufferTime"),wc=class extends V{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)}},WI=G(wc,"delay"),Vc=class extends V{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},JI=G(Vc,"catchError");var Uc=class extends V{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)}))}},QI=G(Uc,"tap"),Bc=class extends V{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()}},zI=G(Bc,"timeout");var mA=Vu(Uu(250),Bu(()=>performance.now()),oo());var Nr=new Map;T.on(f.JOIN_SUCCESS,({room:r})=>{ge(r.userId,{eventId:32788,eventDesc:"join room"})});T.on(f.LEAVE_START,({room:r})=>{ge(r.userId,{eventId:32789,eventDesc:"leave room"})});T.on(f.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ge(r.room.userId,{eventId:i,eventDesc:`publish ${r.kind}`})}});T.on(f.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ge(r.room.userId,{eventId:i,eventDesc:`unpublish ${r.kind}`})}});T.on(f.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ge(r.room.userId,{eventId:r.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:r.isRemote?r.userId:void 0}):ge(r.room.userId,{eventId:r.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:r.isRemote?r.userId:void 0}))});T.on(f.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ge(r.room.userId,{eventId:r.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:r.isRemote?r.userId:void 0}):ge(r.room.userId,{eventId:r.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:r.isRemote?r.userId:void 0}))});T.on(f.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ge(r.room.userId,{eventId:32777,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&ge(r.room.userId,{eventId:32776,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&ge(r.room.userId,{eventId:32803,eventDesc:`${h.SUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});T.on(f.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ge(r.room.userId,{eventId:32779,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&ge(r.room.userId,{eventId:32778,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&ge(r.room.userId,{eventId:32804,eventDesc:`${h.UNSUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});T.on(f.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ge(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781,eventDesc:`switch ${r.kind===h.VIDEO?"camera":"microphone"}`})});T.on(f.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ge(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783,eventDesc:`replace ${r.kind}`})});T.on(f.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&&ge(r.userId,{eventId:t,eventDesc:s})});T.on(f.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n=s?"downlink":"uplink",o,a;switch(e){case"CONNECTED":i==="RECONNECTING"?(o=s?32801:32798,a=`${n} reconnected`):(o=s?32793:32792,a=`${n} connected`);break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799,a=`${n} reconnect fail`);break;case"RECONNECTING":o=s?32800:32797,a=`${n} reconnecting`;break}o&&a&&ge(r.userId,{eventId:o,eventDesc:a,remoteUserId:t})});function ge(r,i){let e=M(N({},i),{timestamp:Hr()});Nr.has(r)?Nr.get(r).push(e):Nr.set(r,[e])}function $u(r){if(Nr.has(r)){let i=Nr.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return Nr.delete(r),i}return[]}var Hu=ve(Ve(),1);var po=class extends Hu.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===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 n=`peer leave [${e}]`;E(t)||(n+=`:${sa[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.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(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=_i(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:_i(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Fu({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return F((t,s)=>{let n=new Map;return T.on(f.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.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(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new C({code:S.INVALID_OPERATION,message:D({key:v.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...o)}})}var Gu=!0,Wu=function(){var r;Gu&&(Gu=!1,A.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${lt}/en/index.html`),console.info(`* Changelog: ${lt}/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:",Te),A.info("UA:",navigator.userAgent),A.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),as().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 vt={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 x={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},Ot=(I=>(I[I.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",I[I.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",I[I.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",I[I.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",I[I.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",I[I.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",I[I.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",I[I.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",I[I.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",I[I.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",I[I.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",I[I.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",I[I.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",I[I.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",I[I.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",I[I.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",I[I.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",I[I.INVALID_OPERATION=5100]="INVALID_OPERATION",I[I.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",I[I.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",I[I.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",I[I.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",I[I.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",I[I.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",I[I.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",I[I.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",I[I.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",I[I.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",I[I.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",I[I.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",I[I.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",I[I.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",I[I.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",I[I.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",I[I.DEVICE_ERROR=5300]="DEVICE_ERROR",I[I.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",I[I.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",I[I.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",I[I.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",I[I.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",I[I.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",I[I.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",I[I.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",I[I.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",I[I.SERVER_ERROR=5400]="SERVER_ERROR",I[I.NEED_TO_BUY=5401]="NEED_TO_BUY",I[I.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",I[I.OPERATION_FAILED=5500]="OPERATION_FAILED",I[I.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",I[I.REJOIN_FAILED=5502]="REJOIN_FAILED",I[I.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",I[I.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",I[I.OPERATION_ABORT=5998]="OPERATION_ABORT",I[I.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",I))(Ot||{});function ju({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=Ot[r];try{s=Ju[n]}catch(o){s=Ju.UNKNOWN_ERROR}return Q(s)?t=s(i):z(s)&&(t=s),e&&(t+=" doc:"),t}var Ju=M(N({},Ee),{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}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${he(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}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${he(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}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",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}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},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.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:i=Bi(r),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Bi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var $i=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=ju({code:t||e,params:N({fnName:o,error:a},n)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Ot[e],this.code=e,this.extraCode=t,this.functionName=o,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");ui?_.href=`ms-settings:privacy-${m[this.functionName]}`:pt&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof C){let{stack:o}=e,a={code:x.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=x.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=x.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=x.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ee.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=x.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=x.OPERATION_ABORT;break;case S.DEVICE_NOT_FOUND:case S.DEVICE_AUTO_RECOVER_FAILED:case S.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=fp(e.name));break;case S.UNKNOWN:break;default:a.code=x.OPERATION_FAILED}n=new $i(a),o&&(n.stack+=o.substr(o.indexOf(`
|
|
32
|
+
`)))}else{if(e instanceof $i)return e;n=new $i({code:x.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function fp(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 k=$i;var Ku={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Xu={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}}},br={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:x.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Qu={name:"userId",required:!0,type:"string"},zu={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[vt.AUDIO_PROFILE_STANDARD,vt.AUDIO_PROFILE_STANDARD_STEREO,vt.AUDIO_PROFILE_HIGH,vt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function fo(r,i){if(!r)throw new k({code:x.INVALID_OPERATION,extraCode:5101,fnName:i})}function qu(r,i,e){if(!r)throw new k({code:x.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var sC={type:"number",notLessThanZero:!0},Ep={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 k({code:x.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:x.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:x.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 k({code:x.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:x.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:br,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Ku},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Jt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:M(N({},br),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Ku}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:zu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Jt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:zu}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:br,publish:{type:"boolean"},option:Xu},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&Jt())throw new k({code:x.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ts())throw new k({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:br,publish:{type:"boolean"},option:Xu}},muteRemoteAudio:[Qu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Qu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:br,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){fo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(qu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:x.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:M(N({},br),{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){fo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(qu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:x.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!=="*"&&E(r.streamType))throw new k({code:x.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){fo(this._room.isJoining||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(!Ei)throw new k({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:x.INVALID_OPERATION,messageParams:{key:v.SEI_DISABLED}});if(r.byteLength>1e3)throw new k({code:x.INVALID_PARAMETER,messageParams:{key:v.SEI_OVERSIZE,data:r.byteLength}});if(r.byteLength===0)throw new k({code:x.INVALID_PARAMETER,messageParams:{key:v.SEI_EMPTY}});if(fo(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new k({code:x.INVALID_PARAMETER,messageParams:{key:v.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},Se={TRTC:Ep};var Ne=class extends Error{};function gp(r,i){let e=hr(r);for(let t=0;t<i.length;t++)Ht(e[t],i[t]);return e}function Tp(r){this._resolve=Promise.resolve(r)}function Sp(r){this._reject=Promise.reject(r)}var vr=class{constructor(i,e){this.instance=i;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",gp);let t=vr.instances.get(i);t?t.set(e,this):vr.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=vr.instances.get(i);return t&&t.get(e)||new vr(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},n=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Ne("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:Tp,reject:Sp};try{switch(this.state){case 1:if(i===0)throw new Ne("already started");break;case 4:if(i===2)throw new Ne("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Ne("already start");break;case 3:switch(i.type){case 2:throw new Ne("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ne("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Ne("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 Ne("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ne("start not allowed after update");case 0:throw new Ne("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Ne("keep start")),new Ne("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}},ei=vr;u(ei,"instances",new WeakMap);var Eo=new WeakMap,go=(r,i)=>{if(i instanceof Ne){let{stack:e}=i;i=new k({code:x.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
33
|
+
`)))}throw i};function Si(r,i){return F((e,t)=>function(...s){let n=ei.get(this,typeof r=="string"?r:r.call(this,...s));return i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(go.bind(null,t))})}function Hi(r,i){let{merge:e,debounce:t}=i||{};return F((s,n)=>function(...o){let a=ei.get(this,typeof r=="string"?r:r.call(this,...o));if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,o)){let{delay:c,getKey:d}=t;return new Promise((l,m)=>{var R,y;let _=(R=Eo.get(this))==null?void 0:R.get(d(...o));if(_){let{timeoutId:L,resolve:ie}=_;clearTimeout(L),ie()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(go.bind(null,n)).then(l,m)},c);Eo.has(this)?(y=Eo.get(this))==null||y.set(d(...o),{timeoutId:g,resolve:l}):Eo.set(this,new Map([[d(...o),{timeoutId:g,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(go.bind(null,n))})}function Ii(r){return F((i,e)=>function(...t){return ei.get(this,typeof r=="string"?r:r.call(this,...t)).action(3,i.bind(this),t).catch(go.bind(null,e))})}var $={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",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",TRACK:"track"};function ws(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Vs(r){return r===vt.QOS_PREFERENCE_CLEAR?"detail":r===vt.QOS_PREFERENCE_SMOOTH?"motion":""}function el(r,i,e){return{room:r,assetsPath:e,innerEmitter:T,constants:na,environment:dr,utils:De,eventLogger:ee,log:r.getLogger(),errorModule:i,kvStatManager:P,clearStarted(t,s){let n=t.getAlias(),o=ei.instances.get(r);if(!!o)if(s){let a=o.get(n+s);if(!a)return;a.started=!1}else o.forEach((a,c)=>{c.startsWith(n)&&(a.started=!1)})}}}var tl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=D({key:v.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${n}
|
|
105
34
|
|
|
106
|
-
${s.stack}`),!1}},r};var To=new WeakMap;function sl(r,i){return F((e,t)=>function(...s){var a,c;let n=(a=To.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);To.has(this)?(c=To.get(this))==null||c.set(i(...s),o):To.set(this,new Map([[i(...s),o]]))})}var nl="5.6.0-beta.7";function ke(...r){return F((i,e)=>function(...t){try{So.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function $c(...r){return F((i,e)=>function(...t){try{So.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function So(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)go.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else go.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function go({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:x.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new k(n(5001));if(E(r.defaultValue)){Q(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 d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),Q(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&me(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:x.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>fs(d)?xn(d):z(d)?d:me(d))},value:i}})}else if(!E(r.type)&&me(i)!==r.type)throw new k(n(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(n(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(n(5006));if(!E(r.min)&&ee(i)&&i<r.min)throw new k(n(5007));if(!E(r.max)&&ee(i)&&i>r.max)throw new k(n(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(n(5004))}else if(Q(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(n(5005));let{properties:o}=r;$e(o)&&ct(i)&&Object.keys(o).forEach(c=>{go.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;$e(a)&&de(i)&&i.forEach((c,d)=>{go.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),Q(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return F((s,n)=>function(...o){function a(l,m,_){if(_&&_.includes(l))return"hided";if(e){let T=e(...o);if(o[T.argIndex]===m)return T.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${me(m)}`:(JSON.stringify(m),m)}catch(T){return`type:${me(m)}`}}let c=this._log||A;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):ja[n];try{let l=s.apply(this,o),m=U();return _s(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),B.addSuccessEvent({key:d,cost:U()-m}),_)).catch(_=>{throw _=k.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),B.addFailedEvent({key:d,error:_}),_}):(B.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),B.addFailedEvent({key:d,error:l}),l}})}var Io=r=>F((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:x.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return So.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Ao=0,Hc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Ar(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}},Mr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Ao=Ao+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ao}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ao}`),this.core=i}getName(){return Mr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule;case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new Hc(i,e.audioManager),this.cacheMusicMap.set(t,n)),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),B.addEnum({key:502700,value:3})})}update(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:n,seekFrom:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}E(t)||(a.volume=t),E(s)||(a.loop=s),E(n)||a.setOperation(n),E(o)||a.seek(o)})}stop(e){return p(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Ci=Mr;u(Ci,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:x.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:x.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t})}}),u(Ci,"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"]}}}),u(Ci,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Ci,"Name","AudioMixer");var ol=r=>(r=Number(r),r>0&&r<14e8);var Ro=0,Lr=class{constructor(i){this.core=i;u(this,"log");u(this,"workletReady");u(this,"audioContext",we("denoiser"));u(this,"workletNode");Ro=Ro+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ro}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ro}`),i.assetsPath&&(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(e=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${e}`)}))}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,n){if(!i.room.audioManager.hasAudioTrack)throw new k({code:x.INVALID_OPERATION,extraCode:5106,fnName:s})}}}getName(){return Lr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Lr.startValidateRule(this.core);case"update":return Lr.updateValidateRule;case"stop":return Lr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;if(this.workletReady||(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(t=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${t}`)})),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield bp(L(y({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:x.INVALID_PARAMETER,message:a});yield this.workletReady,this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return p(this,null,function*(){})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},Ji=Lr;u(Ji,"updateValidateRule",{type:"object"}),u(Ji,"stopValidateRule",{type:"object"}),u(Ji,"Name","AIDenoiser");var al={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Np(r){let i;return ol(r)?i=al.MAIN_OVERSEA:i=al.MAIN,i}function bp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${Np(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let _="Init RTCAIDenoiser failed.",T="";switch(c){case 1:T="Please check your params.";break;case 2:T="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:T="Server is invalid. Please contact our engineer. ";break;case 4:T="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:T="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:T="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${_} Reason: ${d}. ${T}`:`${_}, ${T}`}})}var cl=0,Fc=new Set,be=null;ta(nl);var vp={RtcError:k,ErrorCode:x,ErrorCodeDictionary:kt},$s=class extends ul.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",A.createLogger({id:`t${++cl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(y({logger:this._log,frameWorkType:$s.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Ci,t.assetsPath),this._use(Ji,t.assetsPath),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new k({code:x.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),rl(this,"trtc")}static create(e){}static _create(e,t){ju();let s=new $s(e,t||{});return Fc.add(s),s}_listenEvents(){Pe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{Pe(s,s).add("player-state-changed",n=>{let o=L(y({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Us(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===S.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),n!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:x.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,L(y({},e),{streamType:Us(e.streamType)}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/ot},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/ot},video:_.msg_video_status.map(T=>({bitrate:(T.uint32_video_codec_bitrate||0)/1e3,width:T.uint32_video_width,height:T.uint32_video_height,frameRate:T.uint32_video_dec_fps,videoType:t[T.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}),Pe(this,_e).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),be&&be.deviceId===us){let t=(yield yr()).find(s=>s.deviceId===us);t&&be.groupId!==t.groupId&&(be=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield yr())[0];t&&be&&(be.deviceId===e.deviceId||be.deviceId===us&&be.groupId!==t.groupId)&&(be=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let n=new e(il(this._room,vp,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,ue(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),yield this._room.join(a,t,$s.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pe(this),this.removeAllListeners(),this._room.destroy(),Fc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>e.destroy())}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,mute:s,option:n}=e,o=new ye(this._room.audioManager),a={},c={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&ee(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),E(n.profile)||(z(n.profile)?bn[n.profile]&&o.setProfile(bn[n.profile]):o.setProfile(n.profile)),ee(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),E(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new k({code:x.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,L(y({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),E(s)||o.setMute(s),Pe(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,L(y({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=L(y({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Wt(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(),this._room.audioManager.removeInput(this._localAudioTrack),pe(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,mute:n,option:o}=e,a=new ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:E(o.useFrontCamera)?E(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(o.profile)||(z(o.profile)?Xe[o.profile]&&a.setProfile(Xe[o.profile]):a.setProfile(o.profile)),E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),E(o.small)||(Rs()?z(o.small)?a.small=Xe[o.small]:o.small===!0?a.small=Xe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:x.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,L(y({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(n)||(yield a.setMute(n)),(o==null?void 0:o.qosPreference)&&a.mediaTrack){let l=Bs(o.qosPreference);a.mediaTrack.contentHint=l}Pe(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(y({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(y({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(E(o.profile)||(z(o.profile)?Xe[o.profile]&&this._localVideoTrack.setProfile(Xe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&E(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):E(o.useFrontCamera)?E(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(o.fillMode)||(a.objectFit=o.fillMode),E(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Bs(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Rs()?(o.small===!0?this._localVideoTrack.small=Xe["120p"]:z(o.small)?this._localVideoTrack.small=Xe[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Wt(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(),pe(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:n}=e,o=new Ge(this._room.videoManager);o.on("4",m=>{let _;m.error&&(_=k.convertFrom(m.error)),this.emit($.PUBLISH_STATE_CHANGED,L(y({},m),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(E(n.profile)||(z(n.profile)?vn[n.profile]&&o.setProfile(vn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),E(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Bs(n.qosPreference);o.mediaTrack.contentHint=m}if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new vt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Pe(o,o).add("player-state-changed",m=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(y({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=L(y({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(E(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Bs(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Wt(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:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),n==="main"&&!E(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),o&&!E(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var M,re;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:_}=c;n==="main"&&o&&!E(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),Wt(_,e);let T=E(o==null?void 0:o.receiveWhenViewVisible)?(M=_.option)==null?void 0:M.receiveWhenViewVisible:o.receiveWhenViewVisible,C=E(t)?_.view:t,R=E(o==null?void 0:o.viewRoot)?(re=_.option)==null?void 0:re.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:C,receiveWhenViewVisible:T,viewRoot:R})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),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 n of s)n.muteState.hasAudio&&(yield this._startRemoteAudio({userId:n.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 n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.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 this.listeners(e).includes(t)?this:(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 n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(z(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.mediaTrack)||null;return null}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(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 n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(E(s.volume)||(o.volume=s.volume));let a=n.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_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._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),E(e)&&n&&n.view&&!Ra(t)){let a=Ts(n.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=Ts(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Us(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;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),(n=this._localScreenConfig)!=null&&n.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:n}){if(E(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Us(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(_=>{_.forEach(T=>{d.set(T.target,T.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(C=>C)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:n}));let m=new Set(Ts(t));d.forEach((_,T)=>{m.has(T)||(a.unobserve(T),d.delete(T))}),m.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_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=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(be&&!Cr(be))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:be});else{let e=yield yr();if(e[0]&&!Cr(e[0]))be=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!be||Cr(be))&&(this._initActiveSpeaker(),g.off("102",this._initActiveSpeaker))};g.on("102",t)}}})}_onAudioAvailable({userId:e}){!this._room.autoReceiveAudio||this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e)||this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}static setLogLevel(e,t){A.setLogLevel(e),E(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Bn()}static getCameraList(){return Fe(!0)}static getMicrophoneList(){return Ve(!0)}static getSpeakerList(){return yr(!0)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield yr()).forEach(s=>{s.deviceId===e&&(Fc.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),be=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(Bi.version=a),e){case"count":Bi.addCount({key:t,useUV:o});break;case"enum":Bi.addEnum({key:t,value:s,useUV:o});break;case"number":Bi.addNumber({key:t,value:s,split:n});break}}},K=$s;u(K,"_loggerManager",A),u(K,"EVENT",$),u(K,"ERROR_CODE",x),u(K,"TYPE",Dt),u(K,"frameWorkType",30),b([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],K.prototype,"use",1),b([ke(Ie.TRTC.enterRoom),Ai("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),F(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],K.prototype,"enterRoom",1),b([ne()],K.prototype,"exitRoom",1),b([ke(Ie.TRTC.switchRole),Wi("room",{merge:(r,i)=>i}),ne()],K.prototype,"switchRole",1),b([ne()],K.prototype,"destroy",1),b([ke(Ie.TRTC.startLocalAudio),Ai("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)}),ne()],K.prototype,"startLocalAudio",1),b([ke(Ie.TRTC.updateLocalAudio),Wi("audio",{debounce:{delay:200,getKey:()=>`${cl}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],K.prototype,"updateLocalAudio",1),b([Ri("audio"),ne()],K.prototype,"stopLocalAudio",1),b([ke(Ie.TRTC.startLocalVideo),Ai("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)}),ne()],K.prototype,"startLocalVideo",1),b([ke(Ie.TRTC.updateLocalVideo),Wi("video"),ne()],K.prototype,"updateLocalVideo",1),b([Ri("video"),ne()],K.prototype,"stopLocalVideo",1),b([ke(Ie.TRTC.startScreenShare),Ai("screen",()=>!0),ne()],K.prototype,"startScreenShare",1),b([ke(Ie.TRTC.updateScreenShare),Wi("screen"),ne()],K.prototype,"updateScreenShare",1),b([ne()],K.prototype,"stopScreenShare",1),b([ke(Ie.TRTC.startRemoteVideo),Ai(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"startRemoteVideo",1),b([ke(Ie.TRTC.updateRemoteVideo),Wi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"updateRemoteVideo",1),b([ke(Ie.TRTC.stopRemoteVideo),F(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)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"stopRemoteVideo",1),b([Ri(r=>`v${r.userId}${r.streamType}`)],K.prototype,"_stopRemoteVideo",1),b([ke(...Ie.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],K.prototype,"muteRemoteAudio",1),b([$c(...Ie.TRTC.setRemoteAudioVolume),sl(200,r=>r),ne({getRemoteId:r=>r})],K.prototype,"setRemoteAudioVolume",1),b([Io("start"),Ai((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Ka[r.getName()]})],K.prototype,"startPlugin",1),b([Io("update"),Wi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Xa[r.getName()]})],K.prototype,"updatePlugin",1),b([Io("stop"),Ri((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>za[r.getName()]})],K.prototype,"stopPlugin",1),b([$c(...Ie.TRTC.enableAudioVolumeEvaluation)],K.prototype,"enableAudioVolumeEvaluation",1),b([ne()],K.prototype,"setCurrentSpeaker",1),b([Ai(r=>`a${r.userId}`,()=>!0)],K.prototype,"_startRemoteAudio",1),b([F(r=>function(i){return p(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(y({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Ri(r=>`a${r.userId}`)],K.prototype,"_stopRemoteAudio",1),b([Ri("room")],K.prototype,"_exitRoom",1),b([Ri("screen")],K.prototype,"_stopScreenShare",1),b([ke(Ie.TRTC.sendSEIMessage),Wu({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],K.prototype,"sendSEIMessage",1),b([ne()],K.prototype,"getVideoSnapshot",1),b([ke(Ie.TRTC.create)],K,"_create",1);var Hs=K;var Gc=class{constructor(){this._set=new Set;g.on(f.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 Op(){return p(this,null,function*(){let r,i;try{let m=yield Ve();r=m&&m.length}catch(m){}try{let m=yield Fe();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=zt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};te.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),te.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function ll(){return F(r=>{let i=new Gc;return function(e,t,s){return p(this,null,function*(){let n=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 N({code:S.INVALID_OPERATION,message:O({key:v.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new N({code:S.INVALID_OPERATION,message:O({key:v.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),g.emit(f.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield zt.checkSystemRequirementsInternal(),this.checkDestroy();let o=De.getEnv();o||(o=$t.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(On.OLD_CLOUD_LADDER)?o=$t.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(On.WEBRTC)&&(o=$t.WEBRTC))),te.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Op.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!zt.isWebRTCSupported()||!a&&!c)throw new N({code:S.NOT_SUPPORTED,message:O({key:v.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!De.getEnv()&&(yield this.schedule(n,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=De.performanceNow(),g.emit(f.JOIN_SUCCESS,{room:this}),te.uploadEvent({log:`stat-conv-${Number(it)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),g.emit(f.JOIN_FAILED,{room:this,error:d}),d}})}})}var hl=()=>F(r=>function(...i){return p(this,null,function*(){g.emit(f.LEAVE_START,{room:this}),yield r.call(this),g.emit(f.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function ml(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var _l=ve(Ue(),1);var pl=Symbol("instance"),cb=Symbol("abortCtrl"),Wc=Symbol("cacheResult"),ji=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Ws.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Fs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Dp(r){return typeof r=="object"&&r&&"then"in r}var Gs=new Map;function Jc(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Gs.get(t)||[];Gs.has(t)||Gs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=ie.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[Wc];d.state instanceof ji&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof ji&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Fs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Fs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,_=new ji(m,i,o);Ws.call(d,_);let T=R=>{var M;return d[Wc]=R,_.aborted||(Ws.call(d,i),(M=e.success)===null||M===void 0||M.call(this,d[Wc])),R},C=R=>{let M=R instanceof Error?R.message:String(R);if(Ws.call(d,m,R),e.fail)e.fail.call(this,new Fs(d._state,`action '${o}' failed :${M}`,R instanceof Error?R:new Error(M)));else{if(e.ignoreError)return R;throw R}};try{let R=a.apply(this,c);return Dp(R)?R.then(T).catch(C):T(R)}catch(R){C(R)}}}}var kp=(()=>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 Ws(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(ie.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var ie=class extends _l.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ie.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[pl];s?this.name=s.name+"-"+s.count++:t[pl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Gs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Gs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=ie.instances.get(i),e||ie.instances.set(i,e=new ie(i,void 0,Object.create(ie.prototype)))):(e=ie.instances2.get(i),e||ie.instances2.set(i,e=new ie(i.constructor.name,void 0,Object.create(ie.prototype)))),e}static getState(i){var e;return(e=ie.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){kp(ie.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Ws.call(this,i)}};ie.STATECHANGED="stateChanged";ie.UPDATEAFSM="updateAFSM";ie.INIT="[*]";ie.ON="on";ie.OFF="off";ie.instances=new Map;ie.instances2=new WeakMap;var El=ve(Ue());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Mt={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,SERVER_FIRST_PACKAGE_RECEIVED:5e3},fl=[Mt.UPDATE_REMOTE_MUTE_STAT,Mt.UPLINK_NETWORK_STATS,Mt.USER_LIST_RES,Mt.MUTE_RESULT,Mt.SERVER_FIRST_PACKAGE_RECEIVED],V={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",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received"},X={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",RECONNECT_WS:"reconnect"};var ri=new WeakMap;function yi({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=Tt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var _;(_=ri.get(s))!=null&&_.has(n)?d():l(c)},l,m)},onRetrying(c,d){var l;Q(e)&&e.call(this,c,d),(l=ri.get(s))!=null&&l.has(n)&&(ri.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=ri.get(s);return d?d.set(n,{args:c}):ri.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=ri.get(s))==null?void 0:l.delete(n)})},o}}function Js({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=ri.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=ri.get(t).get(r),_=!0;if(e){for(let T of m)if(!a.find(C=>C===T)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=ri.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var Co=new Set;function Tl(r){let i=[...Co.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var xr=class extends El.default{constructor(e){var s,n;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);this.room=e.room,this.race=E(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-Co.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Co.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}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=U();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield ms(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new N({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.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}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Pn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(Mt),c=Object.keys(Mt)[o.indexOf(s)],d=V[c];switch(fl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Mt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Id(n.svrTime),this._log.info("ChannelSetup Success"),B.addSuccessEvent({key:521701,cost:U()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new N({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:O({key:v.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),B.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case Mt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{St(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:X.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),B.addSuccessEvent({key:521702,cost:U()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(B.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}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},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Pn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let T=new N({code:S.API_CALL_TIMEOUT,message:O({key:v.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(T),d(T)},s),m=T=>{T.data.seq===_&&(clearTimeout(l),this.off(n,m),c(T))};this.on(n,m);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return Tt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),Co.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("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=n=>{n instanceof ji&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(ie.STATECHANGED,s))};this.room.on(ie.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([yi({settings:{retries:1/0,timeout:2e3},onError(r,i){this.room.isDestroyed||i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,this.room.isDestroyed&&i())}})],xr.prototype,"connect",1);var gl=ve(Ue());var jc=0,Kc=!1,No=new Set,Lp=r=>jc>2&&!Kc&&No.size===0&&r,Xc=!1,We=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new gl.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_enableSEI");u(this,"_sei");u(this,"_localAddress");u(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-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=U())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,B.addSuccessEvent({key:521705,cost:Math.min(U()-this._prevTime,30*1e3)})):this._isReconnecting&&B.addSuccessEvent({key:521706,cost:U()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,B.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&B.addFailedEvent({key:521706,error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Vi,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),No.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 N({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return st;let i=null;if(this._isUplink){if(!Sr()||this._peerConnection.getSenders().length===0)return st;i=this._peerConnection.getSenders()[0].transport}else{if(!wi()||this._peerConnection.getReceivers().length===0)return st;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:st}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===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,n=new N({message:s,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),te.logSuccessEvent({userId:this._room.userId,eventType:Le.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jc=0,Kc=!1,Xc=!0,No.add(this)):No.delete(this),g.emit(f.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(Ti(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(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new N({code:S.API_CALL_ABORTED,message:O({key:v.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{g.off(f.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new N({code:S.API_CALL_TIMEOUT,message:"connection timeout"});jc+=1,Lp(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),Kc=!0,this._emitter.emit("firewall-restriction")),e(a)},ds);g.on(f.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(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ft()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new N({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:O({key:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.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(le.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 qc=ve(Yc());var ce=function(r){return qc.default.parse(r)},qe=function(r){return qc.default.write(r)},bl=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),qe(i)};function vl(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),qe(i)}function bo(r){return Object.keys(r).filter(i=>r[i])}var ed=class extends We{constructor(e){super(L(y({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new Zt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ot(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Nr(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 Ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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 n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===cs?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
|
|
35
|
+
${s.stack}`),!1}},r};var To=new WeakMap;function il(r,i){return F((e,t)=>function(...s){var a,c;let n=(a=To.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);To.has(this)?(c=To.get(this))==null||c.set(i(...s),o):To.set(this,new Map([[i(...s),o]]))})}var rl="5.6.0-beta.8";function ke(...r){return F((i,e)=>function(...t){try{Io.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function $c(...r){return F((i,e)=>function(...t){try{Io.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Io(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)So.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else So.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function So({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:x.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new k(n(5001));if(E(r.defaultValue)){Q(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 d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),Q(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:x.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>ms(d)?xn(d):z(d)?d:he(d))},value:i}})}else if(!E(r.type)&&he(i)!==r.type)throw new k(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new k(n(5006));if(!E(r.min)&&re(i)&&i<r.min)throw new k(n(5007));if(!E(r.max)&&re(i)&&i>r.max)throw new k(n(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(n(5004))}else if(Q(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(n(5005));let{properties:o}=r;Be(o)&&at(i)&&Object.keys(o).forEach(c=>{So.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Be(a)&&de(i)&&i.forEach((c,d)=>{So.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),Q(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return F((s,n)=>function(...o){function a(l,m,_){if(_&&_.includes(l))return"hided";if(e){let g=e(...o);if(o[g.argIndex]===m)return g.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${he(m)}`:(JSON.stringify(m),m)}catch(g){return`type:${he(m)}`}}let c=this._log||A;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):ja[n];try{let l=s.apply(this,o),m=B();return hs(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),P.addSuccessEvent({key:d,cost:B()-m}),_)).catch(_=>{throw _=k.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),P.addFailedEvent({key:d,error:_}),_}):(P.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),P.addFailedEvent({key:d,error:l}),l}})}var Ao=r=>F((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:x.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Io.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Ro=0,Hc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new gr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}},Or=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Ro=Ro+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ro}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ro}`),this.core=i}getName(){return Or.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Or.startValidateRule;case"update":return Or.updateValidateRule;case"stop":return Or.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new Hc(i,e.audioManager),this.cacheMusicMap.set(t,n)),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),P.addEnum({key:502700,value:3})})}update(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:n,seekFrom:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}E(t)||(a.volume=t),E(s)||(a.loop=s),E(n)||a.setOperation(n),E(o)||a.seek(o)})}stop(e){return p(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Ai=Or;u(Ai,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:x.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:x.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t})}}),u(Ai,"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"]}}}),u(Ai,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Ai,"Name","AudioMixer");var sl=r=>(r=Number(r),r>0&&r<14e8);var Co=0,Dr=class{constructor(i){this.core=i;u(this,"log");u(this,"workletReady");u(this,"audioContext",$e("denoiser"));u(this,"workletNode");Co=Co+1,this.log=i.log.createChild({id:`${this.getAlias()}${Co}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Co}`),i.assetsPath&&(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(e=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${e}`)}))}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,n){if(!i.room.audioManager.hasAudioTrack)throw new k({code:x.INVALID_OPERATION,extraCode:5106,fnName:s})}}}getName(){return Dr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Dr.startValidateRule(this.core);case"update":return Dr.updateValidateRule;case"stop":return Dr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;if(this.workletReady||(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(t=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${t}`)})),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield Rp(M(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:x.INVALID_PARAMETER,message:a});yield this.workletReady,this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return p(this,null,function*(){})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},Fi=Dr;u(Fi,"updateValidateRule",{type:"object"}),u(Fi,"stopValidateRule",{type:"object"}),u(Fi,"Name","AIDenoiser");var nl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Ap(r){let i;return sl(r)?i=nl.MAIN_OVERSEA:i=nl.MAIN,i}function Rp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${Ap(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let _="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:d?`${_} Reason: ${d}. ${g}`:`${_}, ${g}`}})}var ol=0,Fc=new Set,be=null;Jo(rl);var Cp={RtcError:k,ErrorCode:x,ErrorCodeDictionary:Ot},Us=class extends cl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",A.createLogger({id:`t${++ol}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Us.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Ai,t.assetsPath),this._use(Fi,t.assetsPath),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new k({code:x.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),tl(this,"trtc")}static create(e){}static _create(e,t){Wu();let s=new Us(e,t||{});return Fc.add(s),s}_listenEvents(){Pe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{Pe(s,s).add("player-state-changed",n=>{let o=M(N({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=ws(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===S.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),n!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:x.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,M(N({},e),{streamType:ws(e.streamType)}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/it},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/it},video:_.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}),Pe(this,_e).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),be&&be.deviceId===Xr){let t=(yield Ir()).find(s=>s.deviceId===Xr);t&&be.groupId!==t.groupId&&(be=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Ir())[0];t&&be&&(be.deviceId===e.deviceId||be.deviceId===Xr&&be.groupId!==t.groupId)&&(be=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let n=new e(el(this._room,Cp,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,ue(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:this._room.useStringRoomId=!1,yield this._room.join(a,t,Us.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pe(this),this.removeAllListeners(),this._room.destroy(),Fc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}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,mute:s,option:n}=e,o=new ye(this._room.audioManager),a={},c={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),E(n.profile)||(z(n.profile)?cn[n.profile]&&o.setProfile(cn[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),E(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new k({code:x.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,M(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),E(s)||o.setMute(s),Pe(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,M(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=M(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ht(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(),this._room.audioManager.removeInput(this._localAudioTrack),pe(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,mute:n,option:o}=e,a=new ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:E(o.useFrontCamera)?E(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(o.profile)||(z(o.profile)?Ke[o.profile]&&a.setProfile(Ke[o.profile]):a.setProfile(o.profile)),E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),E(o.small)||(Ss()?z(o.small)?a.small=Ke[o.small]:o.small===!0?a.small=Ke["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:x.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,M(N({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(n)||(yield a.setMute(n)),(o==null?void 0:o.qosPreference)&&a.mediaTrack){let l=Vs(o.qosPreference);a.mediaTrack.contentHint=l}Pe(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,M(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=M(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(E(o.profile)||(z(o.profile)?Ke[o.profile]&&this._localVideoTrack.setProfile(Ke[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&E(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):E(o.useFrontCamera)?E(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(o.fillMode)||(a.objectFit=o.fillMode),E(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Vs(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Ss()?(o.small===!0?this._localVideoTrack.small=Ke["120p"]:z(o.small)?this._localVideoTrack.small=Ke[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ht(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(),pe(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:n}=e,o=new Ge(this._room.videoManager);o.on("4",m=>{let _;m.error&&(_=k.convertFrom(m.error)),this.emit($.PUBLISH_STATE_CHANGED,M(N({},m),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(E(n.profile)||(z(n.profile)?dn[n.profile]&&o.setProfile(dn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),E(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Vs(n.qosPreference);o.mediaTrack.contentHint=m}if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new Nt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Pe(o,o).add("player-state-changed",m=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,M(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=M(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(E(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Vs(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Ht(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:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),n==="main"&&!E(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),o&&!E(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var L,ie;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:_}=c;n==="main"&&o&&!E(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),Ht(_,e);let g=E(o==null?void 0:o.receiveWhenViewVisible)?(L=_.option)==null?void 0:L.receiveWhenViewVisible:o.receiveWhenViewVisible,R=E(t)?_.view:t,y=E(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:g,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),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 n of s)n.muteState.hasAudio&&(yield this._startRemoteAudio({userId:n.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 n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.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 this.listeners(e).includes(t)?this:(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 n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(z(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.mediaTrack)||null;return null}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(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 n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(E(s.volume)||(o.volume=s.volume));let a=n.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_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._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),E(e)&&n&&n.view&&!Ca(t)){let a=_s(n.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=_s(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:ws(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;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),(n=this._localScreenConfig)!=null&&n.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:n}){if(E(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${ws(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(_=>{_.forEach(g=>{d.set(g.target,g.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:n}));let m=new Set(_s(t));d.forEach((_,g)=>{m.has(g)||(a.unobserve(g),d.delete(g))}),m.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_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=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(be&&!Sr(be))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:be});else{let e=yield Ir();if(e[0]&&!Sr(e[0]))be=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!be||Sr(be))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){!this._room.autoReceiveAudio||this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e)||this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}static setLogLevel(e,t){A.setLogLevel(e),E(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Bn()}static getCameraList(){return Fe(!0)}static getMicrophoneList(){return we(!0)}static getSpeakerList(){return Ir(!0)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield Ir()).forEach(s=>{s.deviceId===e&&(Fc.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),be=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(wi.version=a),e){case"count":wi.addCount({key:t,useUV:o});break;case"enum":wi.addEnum({key:t,value:s,useUV:o});break;case"number":wi.addNumber({key:t,value:s,split:n});break}}},K=Us;u(K,"_loggerManager",A),u(K,"EVENT",$),u(K,"ERROR_CODE",x),u(K,"TYPE",vt),u(K,"frameWorkType",30),b([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],K.prototype,"use",1),b([ke(Se.TRTC.enterRoom),Si("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),F(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],K.prototype,"enterRoom",1),b([ne()],K.prototype,"exitRoom",1),b([ke(Se.TRTC.switchRole),Hi("room",{merge:(r,i)=>i}),ne()],K.prototype,"switchRole",1),b([ne()],K.prototype,"destroy",1),b([ke(Se.TRTC.startLocalAudio),Si("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)}),ne()],K.prototype,"startLocalAudio",1),b([ke(Se.TRTC.updateLocalAudio),Hi("audio",{debounce:{delay:200,getKey:()=>`${ol}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],K.prototype,"updateLocalAudio",1),b([Ii("audio"),ne()],K.prototype,"stopLocalAudio",1),b([ke(Se.TRTC.startLocalVideo),Si("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)}),ne()],K.prototype,"startLocalVideo",1),b([ke(Se.TRTC.updateLocalVideo),Hi("video"),ne()],K.prototype,"updateLocalVideo",1),b([Ii("video"),ne()],K.prototype,"stopLocalVideo",1),b([ke(Se.TRTC.startScreenShare),Si("screen",()=>!0),ne()],K.prototype,"startScreenShare",1),b([ke(Se.TRTC.updateScreenShare),Hi("screen"),ne()],K.prototype,"updateScreenShare",1),b([ne()],K.prototype,"stopScreenShare",1),b([ke(Se.TRTC.startRemoteVideo),Si(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"startRemoteVideo",1),b([ke(Se.TRTC.updateRemoteVideo),Hi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"updateRemoteVideo",1),b([ke(Se.TRTC.stopRemoteVideo),F(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)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"stopRemoteVideo",1),b([Ii(r=>`v${r.userId}${r.streamType}`)],K.prototype,"_stopRemoteVideo",1),b([ke(...Se.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],K.prototype,"muteRemoteAudio",1),b([$c(...Se.TRTC.setRemoteAudioVolume),il(200,r=>r),ne({getRemoteId:r=>r})],K.prototype,"setRemoteAudioVolume",1),b([Ao("start"),Si((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Ka[r.getName()]})],K.prototype,"startPlugin",1),b([Ao("update"),Hi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Xa[r.getName()]})],K.prototype,"updatePlugin",1),b([Ao("stop"),Ii((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Qa[r.getName()]})],K.prototype,"stopPlugin",1),b([$c(...Se.TRTC.enableAudioVolumeEvaluation)],K.prototype,"enableAudioVolumeEvaluation",1),b([ne()],K.prototype,"setCurrentSpeaker",1),b([Si(r=>`a${r.userId}`,()=>!0)],K.prototype,"_startRemoteAudio",1),b([F(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)})}),Ii(r=>`a${r.userId}`)],K.prototype,"_stopRemoteAudio",1),b([Ii("room")],K.prototype,"_exitRoom",1),b([Ii("screen")],K.prototype,"_stopScreenShare",1),b([ke(Se.TRTC.sendSEIMessage),Fu({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],K.prototype,"sendSEIMessage",1),b([ne()],K.prototype,"getVideoSnapshot",1),b([ke(Se.TRTC.create)],K,"_create",1);var Bs=K;var Gc=class{constructor(){this._set=new Set;T.on(f.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 yp(){return p(this,null,function*(){let r,i;try{let m=yield we();r=m&&m.length}catch(m){}try{let m=yield Fe();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=jt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function dl(){return F(r=>{let i=new Gc;return function(e,t,s){return p(this,null,function*(){let n=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:S.INVALID_OPERATION,message:D({key:v.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:S.INVALID_OPERATION,message:D({key:v.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(f.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield jt.checkSystemRequirementsInternal(),this.checkDestroy();let o=De.getEnv();o||(o=xt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(un.OLD_CLOUD_LADDER)?o=xt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(un.WEBRTC)&&(o=xt.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),yp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!jt.isWebRTCSupported()||!a&&!c)throw new C({code:S.NOT_SUPPORTED,message:D({key:v.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!De.getEnv()&&(yield this.schedule(n,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=De.performanceNow(),T.emit(f.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(ot)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(f.JOIN_FAILED,{room:this,error:d}),d}})}})}var ul=()=>F(r=>function(...i){return p(this,null,function*(){T.emit(f.LEAVE_START,{room:this}),yield r.call(this),T.emit(f.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function ll(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var ml=ve(Ve(),1);var hl=Symbol("instance"),rb=Symbol("abortCtrl"),Wc=Symbol("cacheResult"),Gi=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Fs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},$s=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Np(r){return typeof r=="object"&&r&&"then"in r}var Hs=new Map;function Jc(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Hs.get(t)||[];Hs.has(t)||Hs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[Wc];d.state instanceof Gi&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof Gi&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new $s(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new $s(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,_=new Gi(m,i,o);Fs.call(d,_);let g=y=>{var L;return d[Wc]=y,_.aborted||(Fs.call(d,i),(L=e.success)===null||L===void 0||L.call(this,d[Wc])),y},R=y=>{let L=y instanceof Error?y.message:String(y);if(Fs.call(d,m,y),e.fail)e.fail.call(this,new $s(d._state,`action '${o}' failed :${L}`,y instanceof Error?y:new Error(L)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Np(y)?y.then(g).catch(R):g(y)}catch(y){R(y)}}}}var bp=(()=>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 Fs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends ml.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.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[hl];s?this.name=s.name+"-"+s.count++:t[hl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Hs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Hs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){bp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Fs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var _l=ve(Ve());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Dt={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,SERVER_FIRST_PACKAGE_RECEIVED:5e3},pl=[Dt.UPDATE_REMOTE_MUTE_STAT,Dt.UPLINK_NETWORK_STATS,Dt.USER_LIST_RES,Dt.MUTE_RESULT,Dt.SERVER_FIRST_PACKAGE_RECEIVED],U={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",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received"},X={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",RECONNECT_WS:"reconnect"};var ti=new WeakMap;function Ri({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=Et({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var _;(_=ti.get(s))!=null&&_.has(n)?d():l(c)},l,m)},onRetrying(c,d){var l;Q(e)&&e.call(this,c,d),(l=ti.get(s))!=null&&l.has(n)&&(ti.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=ti.get(s);return d?d.set(n,{args:c}):ti.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=ti.get(s))==null?void 0:l.delete(n)})},o}}function Gs({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=ti.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=ti.get(t).get(r),_=!0;if(e){for(let g of m)if(!a.find(R=>R===g)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=ti.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var yo=new Set;function fl(r){let i=[...yo.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var kr=class extends _l.default{constructor(e){var s,n;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);this.room=e.room,this.race=E(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-yo.size>0&&this.room.enableSPC&&(this.keepAlive=!0,yo.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}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=B();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield us(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new C({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.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}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Pn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(Dt),c=Object.keys(Dt)[o.indexOf(s)],d=U[c];switch(pl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Dt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Id(n.svrTime),this._log.info("ChannelSetup Success"),P.addSuccessEvent({key:521701,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:D({key:v.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),P.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case Dt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{Tt(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:X.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:U.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),P.addSuccessEvent({key:521702,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(P.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}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},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Pn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let g=new C({code:S.API_CALL_TIMEOUT,message:D({key:v.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(g),d(g)},s),m=g=>{g.data.seq===_&&(clearTimeout(l),this.off(n,m),c(g))};this.on(n,m);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return Et({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),yo.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}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=n=>{n instanceof Gi&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([Ri({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],kr.prototype,"connect",1);var El=ve(Ve());var jc=0,Kc=!1,bo=new Set,Op=r=>jc>2&&!Kc&&bo.size===0&&r,Xc=!1,We=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new El.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_enableSEI");u(this,"_sei");u(this,"_localAddress");u(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-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=B())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,P.addSuccessEvent({key:521705,cost:Math.min(B()-this._prevTime,30*1e3)})):this._isReconnecting&&P.addSuccessEvent({key:521706,cost:B()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,P.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&P.addFailedEvent({key:521706,error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Ei,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),bo.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:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return et;let i=null;if(this._isUplink){if(!fr()||this._peerConnection.getSenders().length===0)return et;i=this._peerConnection.getSenders()[0].transport}else{if(!xi()||this._peerConnection.getReceivers().length===0)return et;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:et}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===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,n=new C({message:s,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:Me.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jc=0,Kc=!1,Xc=!0,bo.add(this)):bo.delete(this),T.emit(f.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(fi(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(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new C({code:S.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(f.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:S.API_CALL_TIMEOUT,message:"connection timeout"});jc+=1,Op(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Kc=!0,this._emitter.emit("firewall-restriction")),e(a)},Kr);T.on(f.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(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=wt()){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?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.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(le.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 Yc=ve(qc());var ce=function(r){return Yc.default.parse(r)},Ye=function(r){return Yc.default.write(r)},yl=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Ye(i)};function Nl(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),Ye(i)}function vo(r){return Object.keys(r).filter(i=>r[i])}var ed=class extends We{constructor(e){super(M(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new qt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new bt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Rr(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 _i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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 n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===jr?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
|
|
107
36
|
`),s=new Map;t.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let n=[...s];for(let o=0;o<n.length;o++){let[a,c]=n[o];t.splice(a+o,0,c)}return t.join(`\r
|
|
108
|
-
`)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),qe(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=ce(e);return s.media.forEach(n=>{!n.ext||(n.ext=n.ext.filter(o=>!t.includes(o.uri)))}),qe(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var s,n;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((n=this._peerConnection)==null?void 0:n.connectionState)===se.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 o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new N({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}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 n=y({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${bo(n)}]`),yield this.sendSubscription(o,n),o==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=X.UNSUBSCRIBE,o=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=X.SUBSCRIBE_CHANGE,o=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new N({code:a.code,message:O({key:v.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,n={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:X.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:V.SUBSCRIBE_RESULT,timeout:ha});if(!this._peerConnection){let a=new N({code:S.INVALID_OPERATION,message:O({key:v.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};ze()&&this._sdpSemantics===hi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:j.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:j.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:j.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield Un();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=vl(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=bl(t.sdp),this._sdpSemantics===hi&&(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:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===ki)throw new N({code:S.NOT_SUPPORTED_H264,message:O({key:v.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new N({code:t,message:O({key:v.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:n,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",L(y({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let n=s.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(cs)});n&&(this.ssrc.audio=Number(n.id))}else{let n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(cs)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(aa)});n&&(this.ssrc.video=Number(n.id)),o&&(this.ssrc.auxiliary=Number(o.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(!(Re(ed.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=It(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}},Ks=ed;b([F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new N({code:S.API_CALL_ABORTED,message:O({key:v.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Ks.prototype,"subscribe",1),b([eo(We.prototype.afterConnect),Zn(We.prototype.beforeConnect)],Ks.prototype,"connect",1);var Zc=Ks;var Dl={voiceActivityDetection:!1},td=class extends We{constructor(e){super(L(y({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(this,"flag",0)}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(At()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.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 o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){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 o;t&&!s&&t.small&&(o=this._room.videoManager.smallTrack),this.sendMediaSettings(),ze()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:o,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:o}),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(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?h.VIDEO:c||h.VIDEO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||h.VIDEO:h.VIDEO,{direction:j.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let _=n?3:1;yield l[_].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:n?h.AUXILIARY:h.BIG}),m.push(_),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(j.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(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),o&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(j.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(j.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}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(!At()){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 n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(y({},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=L(y({},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(j.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:X.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Rt){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:X.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.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(),ze()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===j.INACTIVE&&(yield this.setTransceiverDirection(j.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;At()&&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)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof ae&&e.small){let n=new MediaStream,{smallTrack:o}=this._room.videoManager;n.addTrack(o),this._peerConnection.addTrack(o,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===lr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(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;At()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&Q(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`),ze()?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)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(j.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!q)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
109
|
-
`).map(d=>{if(d.match(new RegExp(`a=(${
|
|
110
|
-
`);n&&(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 o;let t=(o=this._peerConnection)==null?void 0:o.getSenders();if(!t||t.length===0||!e.mediaTrack)return;let s;if(
|
|
111
|
-
`:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return
|
|
37
|
+
`)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),Ye(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=ce(e);return s.media.forEach(n=>{!n.ext||(n.ext=n.ext.filter(o=>!t.includes(o.uri)))}),Ye(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var s,n;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((n=this._peerConnection)==null?void 0:n.connectionState)===se.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 o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new C({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}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 n=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${vo(n)}]`),yield this.sendSubscription(o,n),o==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=X.UNSUBSCRIBE,o=U.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=X.SUBSCRIBE_CHANGE,o=U.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:v.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,n={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:X.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:U.SUBSCRIBE_RESULT,timeout:ia});if(!this._peerConnection){let a=new C({code:S.INVALID_OPERATION,message:D({key:v.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};Qe()&&this._sdpSemantics===ci?(this._peerConnection.addTransceiver(h.AUDIO,{direction:J.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:J.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:J.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield Un();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=Nl(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=yl(t.sdp),this._sdpSemantics===ci&&(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:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===bi)throw new C({code:S.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new C({code:t,message:D({key:v.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:n,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",M(N({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let n=s.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(jr)});n&&(this.ssrc.audio=Number(n.id))}else{let n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(jr)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(qo)});n&&(this.ssrc.video=Number(n.id)),o&&(this.ssrc.auxiliary=Number(o.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(!(Ae(ed.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=St(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}},Js=ed;b([F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:S.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Js.prototype,"subscribe",1),b([Zn(We.prototype.afterConnect),Yn(We.prototype.beforeConnect)],Js.prototype,"connect",1);var Zc=Js;var vl={voiceActivityDetection:!1},td=class extends We{constructor(e){super(M(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(this,"flag",0)}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(It()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.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 o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){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 o;t&&!s&&t.small&&(o=this._room.videoManager.smallTrack),this.sendMediaSettings(),Qe()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:o,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:o}),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(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:J.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?h.VIDEO:c||h.VIDEO,{direction:J.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:J.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||h.VIDEO:h.VIDEO,{direction:J.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let _=n?3:1;yield l[_].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:n?h.AUXILIARY:h.BIG}),m.push(_),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(J.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(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),o&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(J.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(J.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}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(!It()){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 n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(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(J.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:X.PUBLISH_STATE_CHANGE,data:t,responseCommand:U.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,commandDesc:"unpublish",responseCommand:U.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),At){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:X.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:U.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(),Qe()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===J.INACTIVE&&(yield this.setTransceiverDirection(J.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;It()&&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)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof ae&&e.small){let n=new MediaStream,{smallTrack:o}=this._room.videoManager;n.addTrack(o),this._peerConnection.addTrack(o,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===zi||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(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;It()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&Q(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`),Qe()?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)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(J.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!Y)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
38
|
+
`).map(d=>{if(d.match(new RegExp(`a=(${J.INACTIVE}|${J.RECVONLY}|${J.SENDONLY})`))&&a++,t.includes(a)){if(e===J.INACTIVE&&d.includes(`a=${J.RECVONLY}`))return n=!0,`a=${e}`;if(e===J.SENDONLY&&d.includes(`a=${J.INACTIVE}`))return n=!0,`a=${J.RECVONLY}`}return d}).join(`\r
|
|
39
|
+
`);n&&(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 o;let t=(o=this._peerConnection)==null?void 0:o.getSenders();if(!t||t.length===0||!e.mediaTrack)return;let s;if(Qe()?s=e.kind===h.AUDIO?t[0]:t[1]:s=t.find(a=>a.track&&a.track.kind===e.kind),!s)return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${e.kind} track on ${n?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(n?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(vl);Y&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let n=this.updateMediaSettings(),o={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${o.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:X.PUBLISH_CHANGE,data:o,responseCommand:U.UPDATE_OFFER_RESULT,timeout:ta,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),s.sdp&&this.updateSSRC(s.sdp)}catch(s){throw this._log.error(s),s}})}setBandwidth(o){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s,sdp:n}){if(!As())return n?t===h.VIDEO?this.updateVideoBandwidthRestriction(n,e,s):this.updateAudioBandwidthRestriction(n,e):void 0;let a,c=this._peerConnection.getSenders();if(Qe()){let d=0;t===h.VIDEO&&(s===h.SMALL?d=2:s===h.AUXILIARY?d=3:d=1),a=c[d]}else a=c.find(d=>d.track&&d.track.kind===t);if(a){let d=a.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(d),this._log.info(`${s||""}${t} bandwidth ${e} kbps`),n}catch(l){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${l}`),n)return t===h.VIDEO?this.updateVideoBandwidthRestriction(n,e,s):this.updateAudioBandwidthRestriction(n,e)}}return n})}updateVideoBandwidthRestriction(e,t,s){let n="AS";Y&&(n="TIAS",t=t*1e3);let o=0,a=-1;return s===h.SMALL?o=1:s===h.AUXILIARY&&(o=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===o?`${c}b=${n}:${t}\r
|
|
40
|
+
`:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return Y&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
112
41
|
c=IN $2\r
|
|
113
42
|
b=${s}:${t}\r
|
|
114
|
-
`),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(Dl);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:X.PUBLISH,responseCommand:V.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Ge||this.localAuxVideoTrack instanceof Ge,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:n,data:o}=t.data;return s===0?this.acceptAnswer(o):this.checkPublishResultCode(s,n)})}setSDPDirection(e,t,s="all"){let n=ce(e);return n.media.forEach(o=>{(s==="all"||o.type===s)&&(o.direction=t)}),qe(n)}acceptAnswer(e){return p(this,null,function*(){var t,s,n,o,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),_=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(m){let T=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:T})}_&&(c=yield this.setBandwidth({bandwidth:_,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 n,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((n=this.localMainAudioTrack)!=null&&n.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(X.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Re(td.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,responseCommand:V.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=It(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)&&g.emit(f.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,n)=>{if(s.type===h.AUDIO){let o=s.ssrcs&&s.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===lr&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=s.ssrcs&&s.ssrcs[0];if(!o)return;switch(n){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.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===ki?(this._log.error(Ee.NOT_SUPPORTED_H264ENCODE),new N({code:S.NOT_SUPPORTED_H264,message:O({key:v.NOT_SUPPORTED_H264ENCODE})})):new N({code:S.UNKNOWN,message:O({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}},Xs=td;b([F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new N({code:S.API_CALL_ABORTED,message:O({key:v.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Xs.prototype,"publish",1),b([eo(We.prototype.afterConnect),Zn(We.prototype.beforeConnect)],Xs.prototype,"connect",1);var vo=Xs;var zs=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime");u(this,"_prevReport",{});u(this,"_prevEncoderImplementation");u(this,"_prevQualityLimitationReason");u(this,"_prevAuxQualityLimitationReason");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(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(o=>{var a;if(o.type==="outbound-rtp")if((o.mediaType||o.kind)===h.VIDEO){let d,l;if(o.ssrc===s.video?(d=h.VIDEO,l=i.localMainVideoTrack):o.ssrc===s.small?d=h.SMALL:o.ssrc===s.auxiliary&&(l=i.localAuxVideoTrack,d=h.AUXILIARY),!d)return;e[d].bytesSent=o.bytesSent,e[d].packetsSent=o.packetsSent,e[d].framesEncoded=o.framesEncoded,E(o.keyFramesEncoded)||(e[d].keyFramesEncoded=o.keyFramesEncoded),E(o.nackCount)||(e[d].nackCount=o.nackCount),E(o.pliCount)||(e[d].pliCount=o.pliCount),E(o.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=o.retransmittedPacketsSent),E(o.totalEncodeTime)||(e[d].totalEncodeTime=o.totalEncodeTime),E(o.totalPacketSendDelay)||(e[d].totalPacketSendDelay=o.totalPacketSendDelay),o.ssrc===s.video?(!E(o.encoderImplementation)&&this._prevEncoderImplementation!==o.encoderImplementation&&(this._log.info(`encoderImplementation change to ${o.encoderImplementation}`),this._prevEncoderImplementation=o.encoderImplementation),!E(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevQualityLimitationReason=o.qualityLimitationReason)):o.ssrc===s.auxiliary&&!E(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevAuxQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=o.qualityLimitationReason)}else e.audio.bytesSent=o.bytesSent,e.audio.packetsSent=o.packetsSent;else o.type==="candidate-pair"?Ti(o)&&ee(o.currentRoundTripTime)&&(e.rtt=Math.floor(o.currentRoundTripTime*1e3),this.totalBytesSent=o.bytesSent):o.type==="media-source"&&(o.kind===h.AUDIO?(e.audio.audioLevel=o.audioLevel||0,e.audio.totalAudioEnergy=o.totalAudioEnergy||0):o.kind===h.VIDEO&&(o.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=o.framesPerSecond:o.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=o.framesPerSecond:e.small.fpsCapture=o.framesPerSecond));if(!E(o.audioLevel)&&((a=i.localMainAudioTrack)==null?void 0:a.mediaTrack)&&o.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=o.audioLevel||0),!E(o.frameWidth)){let c=h.SMALL;o.trackIdentifier===i.getVideoTrackId(h.VIDEO)||o.ssrc===s.video?c=h.VIDEO:(o.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||o.ssrc===s.auxiliary)&&(c=h.AUXILIARY),e[c].frameWidth=o.frameWidth,e[c].frameHeight=o.frameHeight,e[c].framesSent=o.framesSent}}),i.localMainAudioTrack){let o=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=o,e.audio.audioLevel===0&&(e.audio.audioLevel=o)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent)}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}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,p2pDelay:0,totalJitter:0,totalJitterCount: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:n,subscribeState:o}=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||!n.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,e.audio.p2pDelay=l.stat.end2EndDelay,c.jitterBufferDelay&&(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount),e.hasAudio=!0}else{if(q&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&n.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,n.hasSmall&&o.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&&n.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"&&Ti(c)&&ee(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);E(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)),!E(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(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 n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let o=yield n.getStats(),a=[],c=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);o.forEach(d=>c.has(d.type)&&a.push(d)),this._spcStats=a}i&&(t=yield this.getSenderStats(i));for(let[n,o]of e){let a=yield this.getReceiverStats(o);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(yt(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){if(!yt(i.senderStats)){let l={uint32_audio_level:i.senderStats.audio.audioLevel*ot,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*ot);let m=[];if(i.senderStats.video.bytesSent){let T={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(T)}if(i.senderStats.small.bytesSent){let T={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(T)}if(i.senderStats.auxiliary.bytesSent){let T={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(T)}let _={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:_}}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 _={uint32_audio_p2p_delay:l.audio.p2pDelay,uint32_audio_cache_ms:l.audio.totalJitter,uint32_audio_cache_ms_count:l.audio.totalJitterCount,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=_}if(l.hasVideo){let _=t.get(`${l.userId}_${ca}`),T=_?_.duration:0,C={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:T,uint32_video_dec_fps:l.video.framesDecoded};m.msg_video_status.push(C)}if(l.hasAuxiliary){let _=t.get(`${l.userId}_${da}`),T=_?_.duration:0,C={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:T,uint32_video_dec_fps:l.auxiliary.framesDecoded};m.msg_video_status.push(C)}e.msg_down_stream_info.push(m)});let n=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let l=n.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 _=this.getDifferenceValue(l.uint32_audio_codec_bitrate,m.uint32_audio_codec_bitrate);m.uint32_audio_codec_bitrate=Math.round(_*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_audio_codec_bitrate}}let o=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(l=>{let m=o.find(M=>M.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 _=0,T=0,C=0;m&&l.uint32_video_codec_bitrate>=m.uint32_video_codec_bitrate&&(_=m.uint32_video_codec_bitrate,T=m.uint32_video_enc_fps,C=m.uint32_video_codec_fps);let R=this.getDifferenceValue(_,l.uint32_video_codec_bitrate);l.uint32_video_codec_bitrate=Math.round(R*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(T,l.uint32_video_enc_fps)/s),l.uint32_video_codec_fps=Math.round(this.getDifferenceValue(C,l.uint32_video_codec_fps)/s),wt&&Vt()===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),E(m.uint32_key_frame_count)||(l.uint32_key_frame_count=Math.round(this.getDifferenceValue(m.uint32_key_frame_count,l.uint32_key_frame_count))),E(m.uint32_nack_count)||(l.uint32_nack_count=Math.round(this.getDifferenceValue(m.uint32_nack_count,l.uint32_nack_count))),E(m.uint32_pli_count)||(l.uint32_pli_count=Math.round(this.getDifferenceValue(m.uint32_pli_count,l.uint32_pli_count))),E(m.uint32_video_arq_packets)||(l.uint32_video_arq_packets=Math.round(this.getDifferenceValue(m.uint32_video_arq_packets,l.uint32_video_arq_packets))),E(m.uint32_encode_cost)||(l.uint32_encode_cost=Math.round(this.getDifferenceValue(m.uint32_encode_cost,l.uint32_encode_cost)/s)),E(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=n.msg_down_stream_info;return e.msg_down_stream_info=e.msg_down_stream_info.filter(l=>c.find(m=>m.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid)),e.msg_down_stream_info.forEach(l=>{let m=c.find(_=>_.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid);if(!yt(l.msg_audio_status)&&!yt(m.msg_audio_status)){let _=l.msg_audio_status,T=m.msg_audio_status,C=this.getDifferenceValue(T.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms_count);delete _.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(T.uint32_audio_cache_ms,_.uint32_audio_cache_ms)/C)||0;let R=this.room.remotePublishedUserMap.get(l.msg_user_info.str_identifier);R&&(R.remoteAudioTrack.stat.jitterBufferDelay=_.uint32_audio_cache_ms),_.uint32_audio_origin_lost=this.getDifferenceValue(T.uint32_audio_origin_lost,_.uint32_audio_origin_lost),_.uint32_audio_receive=this.getDifferenceValue(T.uint32_audio_receive,_.uint32_audio_receive),_.uint32_audio_receive+=_.uint32_audio_origin_lost;let M=this.getDifferenceValue(T.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(M*8/s),_.uint32_audio_total_bitrate=Math.round(M*8/s)}else l.msg_audio_status={};if(l.msg_video_status&&m.msg_video_status){let _=m.msg_video_status;l.msg_video_status=l.msg_video_status.filter(C=>_.find(R=>R.uint32_video_stream_type===C.uint32_video_stream_type)),l.msg_video_status.forEach(C=>{let R=_.find(eh=>eh.uint32_video_stream_type===C.uint32_video_stream_type),M=R.uint32_video_receive,re=R.uint32_video_origin_lost,W=R.uint32_video_codec_bitrate,rn=R.uint32_video_receive_fps,Yl=R.uint32_video_dec_fps;C.uint32_video_origin_lost=this.getDifferenceValue(re,C.uint32_video_origin_lost),C.uint32_video_receive=this.getDifferenceValue(M,C.uint32_video_receive)+C.uint32_video_origin_lost;let ql=this.getDifferenceValue(W,C.uint32_video_codec_bitrate);C.uint32_video_codec_bitrate=Math.round(ql*8/s);let Zl=this.getDifferenceValue(rn,C.uint32_video_receive_fps);C.uint32_video_receive_fps=Math.round(Zl/s),C.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Yl,C.uint32_video_dec_fps)/s)})}}),e}getStatsReport(s){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let n={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_cache_ms:0,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}}]},o=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(n))),this.prepareReport({stats:o,report:n,freezeMap:t}),this._prevReportTime=Date.now(),n})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var kl=ve(Ue());var id=class extends kl.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"_uplinkRTT",0);u(this,"_uplinkLoss",0);u(this,"_downlinkRTT",0);u(this,"_downlinkLoss",0);u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(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(V.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(le.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;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=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=t.expectAudPkg+t.expectVidPkg,o=t.recvAudPkg+t.recvVidPkg,a=n-o;n===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/n*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)===se.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:d,totalPacketsLost:l,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m});continue}let _=0,T=this._downlinkPrevStatMap.get(c),C=l-T.totalPacketsLost,R=m-T.totalPacketsReceived;C<=0||R<0?_=0:_=Math.round(C/(C+R)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:_,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:n,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=n,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,n)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!wi())return t;let s=e.getReceivers();try{for(let n=0;n<s.length;n++)(yield s[n].getStats()).forEach(c=>{c.type==="candidate-pair"&&ee(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(n){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==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="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===se.DISCONNECTED||e.connectionState===se.FAILED||e.connectionState===se.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(ft,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];g.emit(f.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(id.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:n,audioDelay:o})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:n,audioDelay:o})}})}},Xi=id;u(Xi,"EVENT_NETWORK_QUALITY","0");function Wp({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return _s(t)?t.catch(s=>A.error(`${r.name}() error observed ${s}`)):t}catch(t){A.error(`${r.name}() error observed ${t}`)}}}var Oo=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};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")&&Q(this[e])&&(this[e]=Wp({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=Z.run(ft,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:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,is().then(i=>{this._basicInfo.string_os_version=rs(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),g.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(f.JOIN_START,this.handleJoinStart).addEvent(f.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(f.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(f.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(f.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(f.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(f.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(f.JOIN_FAILED,this.handleJoinFailed).addEvent(f.LEAVE_START,this.handleLeaveStart).addEvent(f.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(f.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(f.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(f.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(f.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(f.PUBLISH_START,this.handlePublishStart).addEvent(f.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(f.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(f.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(f.PLAY_TRACK_START,this.handlePlayStart).addEvent(f.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(f.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!fi(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(f.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(f.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(f.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(f.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,n=e.hasAuxiliary,o=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&o&&this.handleRemoteStreamAdded(t.userId,"main"),!n&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(f.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)=>g.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&&(E(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),E(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),E(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:n,tcp:o,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}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 N?Number(e.getExtraCode()||e.getCode()):S.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 n={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:L(y({},Jp),{msg_user_info:new Qs({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};n.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,n)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:n,tinyId:o,role:a}=e,c=new Qs({userId:n,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),l=`${n}_${t}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=d),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:n,sendSubscribeCMDTime:d}),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:n,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,n=this._remoteStreamStatMap.get(s);n&&n.subscribedTime===0&&(n.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!fi(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(!fi(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),n=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),n)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&n){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-o.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:n,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,m;n&&(d=n,l=1),o&&(c=o,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,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:n,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:s}=e.msg_audio_status;Math.floor(s/ot*100)>0&&(this._localStreamStat.totalAudioLevel+=s/ot,this._localStreamStat.audioLevelCount++)}t.forEach(s=>{let{msg_user_info:n,msg_audio_status:o,msg_video_status:a}=s,c=n.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(l=>{let m=l.uint32_video_stream_type===2,_=l.uint32_video_stream_type===7,T=`${c}_${m?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(T);if(!!C&&(m&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||_&&(d==null?void 0:d.remoteAuxiliaryTrack))){C.totalVideoFPS+=l.uint32_video_receive_fps,C.totalVideoBitrate+=l.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=l.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=l.uint32_video_height);let R=m?d.remoteVideoTrack:d.remoteAuxiliaryTrack;R.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=R.stat.jitterBufferDelay),R.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(R.stat.framesDecoded/R.stat.framesReceived*Hr(10,6)))}}),o){let l=`${c}_${"main"}`,m=this._remoteStreamStatMap.get(l);this._remoteStreamStatMap.has(l)&&m&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(m.totalAudioBitrate+=o.uint32_audio_codec_bitrate,m.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/ot*100)>0&&(m.totalAudioLevel+=o.uint32_audio_level/ot,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 N?e.getExtraCode()||e.getCode():S.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())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ui)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&li)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Di)>=0}hitTest(i){return i===this._room}checkStorage(){return p(this,null,function*(){try{let i=Jt.getItem(this._storageKey);i&&(yield this.upload(i),Jt.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&&Jt.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:_,videoDelayCount:T,totalAudioDelay:C,totalVideoDelay:R}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/m),_&&C&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(C/_),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),T&&R&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(R/T))}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:n}=this._room;n&&(i.statsToReport.uint32_audio_play_time=n.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=n.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,zi);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.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(d,i.statsToReport.uint32_video_play_time),o.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>zi&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+zi)}),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>zi&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+zi)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>zi&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+zi)}getReportData(){this._basicInfo.uint32_networkType=Er();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Qs({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Es(this._signalInfo.relayIp),uint32_client_ip:Es(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Hr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Es(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return wn(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),Jt.deleteItem(this._storageKey),this.initData()}catch(i){this._log.warn(i)}})}upload(i){return p(this,null,function*(){if(it&&!Qo||i.msg_path_enter_room.uint64_start_time===0||[yn,ia,ra].findIndex(a=>a===location.host)>=0)return;let e=Number(this._room.sdkAppId),t=yield fa(i),s=t instanceof ArrayBuffer,n=`${pi(e,di.KEY_POINT)}&gzip=${+s}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,t)),o||Gt({url:n,body:t}),this.uploadKVStat(B),this.uploadKVStat(Bi)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(y({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield fa(e),s=`${pi(+this._room.sdkAppId,di.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Gt({url:s,body:t})})}};b([yi({settings:{timeout:500,retries:3}})],Oo.prototype,"upload",1);var zi=5e3,Jp={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},Qs=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Ml=Oo;var rd=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=U())}stop(){this._endTime===0&&(this._endTime=U())}getDuration(){return this._endTime===0?U()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},wr=rd;var sd=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(f.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(f.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(f.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var o;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 n=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(s);!n||(!e.hasAudio&&t.hasAudio&&n.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&n.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>g.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>g.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let o=new wr,a=this._durationMap.get(n);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[o],video:[]})}else this.stopDurationItem(n,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let o=new wr,a=this._durationMap.get(n);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[],video:[o]})}else this.stopDurationItem(n,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDurationItem(n,h.AUDIO),this.stopDurationItem(n,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,n=new wr,o=this._durationMap.get(s);o?this.isRecording(o[e])||o[e].push(n):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[n]:[],video:e===h.AUDIO?[]:[n]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(n=>n.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,n)=>s+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Ll=sd;var nd=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(f.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(f.PLAY_TRACK_START,this.onPlayTrackStart).set(f.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDataFreeze({key:n,userId:s,type:e})}).set(f.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 n="main",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}if(e.hasAuxiliary&&!t.hasAuxiliary){let n="auxiliary",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}}).set(f.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!fi(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let n=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(n,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(f.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>g.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>g.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}`,n=this._dataFreezeMap.get(s),o=new wr;n?n.durationItemList.push(o):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[o],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:n,muteState:o}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:n,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 n=s.durationItemList[s.durationItemList.length-1];n.stop();let o=n.getDuration();o>Mn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:o}):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 n=`${i}_${t}`,o=this._renderFreezeMap.get(n);if(e<=2){let a=U();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(n,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=U();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!fi(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()<Mn&&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 n=U(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=n-o.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()}},xl=nd;var Pl=ve(Ue(),1);var jp=[-1,-1,1,-1,-1,1,1,1],Kp=[0,0,1,0,0,1,1,1],Je=class extends P{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"image");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,e instanceof je){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),n=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;n.width=this.width,n.height=this.height,this.ctx2d=n.getContext("2d"),this.image=n,this._canvas=n}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(Kp),this.positionBuffer=this.createBuffer(jp),t.createTexture!==!1&&(this.texture=s.createTexture(),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),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),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=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}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){let t=Date.now();if(this.context instanceof Ae&&this.render(e)||this.context instanceof je&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!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 e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Ae){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,n)=>{s&&(t.activeTexture(t.TEXTURE0+n),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,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.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,n)=>{t.enableVertexAttribArray(n),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(n,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.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;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)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,n,o){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,n,o),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:n,height:o,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:n,height:o,timestamp:d,fps:l,name:a,cost:c},y({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([oe(P.INIT,"connected",{sync:!0})],Je.prototype,"connect",1),b([oe("connected",P.INIT,{ignoreError:!0,sync:!0})],Je.prototype,"disconnect",1),b([oe([],"closed",{sync:!0})],Je.prototype,"close",1);var Xp=[0,1,1,1,0,0,1,0],Ys=class extends Je{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof je?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Xp)}start(e){this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Ae){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Vr=class extends Ys{constructor(e,t){super(e,t);u(this,"_videoTrack");[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let s=n=>{var c;let o=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(n,a)},a=()=>{o(),this.context.destroy(new Error(`video track ${n}`))};this.once("closed",o),(c=this._videoTrack)==null||c.addEventListener(n,a)};e instanceof Ae&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack}},Do=class extends Vr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var ko=class extends Vr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,n=e*t,o=this.resolution.width*this.resolution.height;A.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),n>o?s=n/o:(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=n/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var qs=class extends Je{constructor(e,t,s){super(e,y({name:"imageSource"},s));this.image=t;u(this,"_image");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(s==null?void 0:s.autoResize)!==!1}_render(e,t){let{width:s,height:n}=this;if(this.image instanceof HTMLVideoElement){if(Q(this.image.getVideoPlaybackQuality)&&!ai){let a=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===a)return!1;this._totalFrames=a,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:s,videoHeight:n}=this.image),this.image.width=s,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:n}=this.image,this.image!==this._image)this._image=this.image;else if(s===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:n}=this.image,this._image=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===n&&this.totalFrames){if(t){this.useTexture();let o=this.context.ctx;o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,this.image)}this.resize(s,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ur=class extends qs{constructor(e,t,s){let n=document.createElement("video");n.setAttribute("playsinline","playsinline"),n.setAttribute("muted","");super(e,n,s);this._videoTrack=t;u(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(){var e;super.close(),(e=this._mediaStream)==null||e.removeTrack(this._videoTrack),delete this._mediaStream,this.image.srcObject=null}};var zp=`
|
|
43
|
+
`),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(vl);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:X.PUBLISH,responseCommand:U.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Ge||this.localAuxVideoTrack instanceof Ge,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:n,data:o}=t.data;return s===0?this.acceptAnswer(o):this.checkPublishResultCode(s,n)})}setSDPDirection(e,t,s="all"){let n=ce(e);return n.media.forEach(o=>{(s==="all"||o.type===s)&&(o.direction=t)}),Ye(n)}acceptAnswer(e){return p(this,null,function*(){var t,s,n,o,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),_=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.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})}_&&(c=yield this.setBandwidth({bandwidth:_,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 n,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((n=this.localMainAudioTrack)!=null&&n.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(X.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Ae(td.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,responseCommand:U.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=St(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)&&T.emit(f.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,n)=>{if(s.type===h.AUDIO){let o=s.ssrcs&&s.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===zi&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=s.ssrcs&&s.ssrcs[0];if(!o)return;switch(n){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.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===bi?(this._log.error(Ee.NOT_SUPPORTED_H264ENCODE),new C({code:S.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264ENCODE})})):new C({code:S.UNKNOWN,message:D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:U.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}},js=td;b([F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:S.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],js.prototype,"publish",1),b([Zn(We.prototype.afterConnect),Yn(We.prototype.beforeConnect)],js.prototype,"connect",1);var Oo=js;var Ks=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime");u(this,"_prevReport",{});u(this,"_prevEncoderImplementation");u(this,"_prevQualityLimitationReason");u(this,"_prevAuxQualityLimitationReason");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(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(o=>{var a;if(o.type==="outbound-rtp")if((o.mediaType||o.kind)===h.VIDEO){let d,l;if(o.ssrc===s.video?(d=h.VIDEO,l=i.localMainVideoTrack):o.ssrc===s.small?d=h.SMALL:o.ssrc===s.auxiliary&&(l=i.localAuxVideoTrack,d=h.AUXILIARY),!d)return;e[d].bytesSent=o.bytesSent,e[d].packetsSent=o.packetsSent,e[d].framesEncoded=o.framesEncoded,E(o.keyFramesEncoded)||(e[d].keyFramesEncoded=o.keyFramesEncoded),E(o.nackCount)||(e[d].nackCount=o.nackCount),E(o.pliCount)||(e[d].pliCount=o.pliCount),E(o.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=o.retransmittedPacketsSent),E(o.totalEncodeTime)||(e[d].totalEncodeTime=o.totalEncodeTime),E(o.totalPacketSendDelay)||(e[d].totalPacketSendDelay=o.totalPacketSendDelay),o.ssrc===s.video?(!E(o.encoderImplementation)&&this._prevEncoderImplementation!==o.encoderImplementation&&(this._log.info(`encoderImplementation change to ${o.encoderImplementation}`),this._prevEncoderImplementation=o.encoderImplementation),!E(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevQualityLimitationReason=o.qualityLimitationReason)):o.ssrc===s.auxiliary&&!E(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevAuxQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${o.qualityLimitationReason}`),this._prevAuxQualityLimitationReason=o.qualityLimitationReason)}else e.audio.bytesSent=o.bytesSent,e.audio.packetsSent=o.packetsSent;else o.type==="candidate-pair"?fi(o)&&re(o.currentRoundTripTime)&&(e.rtt=Math.floor(o.currentRoundTripTime*1e3),this.totalBytesSent=o.bytesSent):o.type==="media-source"&&(o.kind===h.AUDIO?(e.audio.audioLevel=o.audioLevel||0,e.audio.totalAudioEnergy=o.totalAudioEnergy||0):o.kind===h.VIDEO&&(o.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=o.framesPerSecond:o.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=o.framesPerSecond:e.small.fpsCapture=o.framesPerSecond));if(!E(o.audioLevel)&&((a=i.localMainAudioTrack)==null?void 0:a.mediaTrack)&&o.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=o.audioLevel||0),!E(o.frameWidth)){let c=h.SMALL;o.trackIdentifier===i.getVideoTrackId(h.VIDEO)||o.ssrc===s.video?c=h.VIDEO:(o.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||o.ssrc===s.auxiliary)&&(c=h.AUXILIARY),e[c].frameWidth=o.frameWidth,e[c].frameHeight=o.frameHeight,e[c].framesSent=o.framesSent}}),i.localMainAudioTrack){let o=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=o,e.audio.audioLevel===0&&(e.audio.audioLevel=o)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent)}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}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,p2pDelay:0,totalJitter:0,totalJitterCount: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:n,subscribeState:o}=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||!n.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,e.audio.p2pDelay=l.stat.end2EndDelay,c.jitterBufferDelay&&(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount),e.hasAudio=!0}else{if(Y&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&n.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,n.hasSmall&&o.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&&n.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"&&fi(c)&&re(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);E(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)),!E(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(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 n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let o=yield n.getStats(),a=[],c=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);o.forEach(d=>c.has(d.type)&&a.push(d)),this._spcStats=a}i&&(t=yield this.getSenderStats(i));for(let[n,o]of e){let a=yield this.getReceiverStats(o);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Ct(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){if(!Ct(i.senderStats)){let l={uint32_audio_level:i.senderStats.audio.audioLevel*it,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*it);let m=[];if(i.senderStats.video.bytesSent){let g={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(g)}if(i.senderStats.small.bytesSent){let g={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(g)}if(i.senderStats.auxiliary.bytesSent){let g={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(g)}let _={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:_}}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 _={uint32_audio_p2p_delay:l.audio.p2pDelay,uint32_audio_cache_ms:l.audio.totalJitter,uint32_audio_cache_ms_count:l.audio.totalJitterCount,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=_}if(l.hasVideo){let _=t.get(`${l.userId}_${Yo}`),g=_?_.duration:0,R={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(R)}if(l.hasAuxiliary){let _=t.get(`${l.userId}_${Zo}`),g=_?_.duration:0,R={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(R)}e.msg_down_stream_info.push(m)});let n=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let l=n.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 _=this.getDifferenceValue(l.uint32_audio_codec_bitrate,m.uint32_audio_codec_bitrate);m.uint32_audio_codec_bitrate=Math.round(_*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_audio_codec_bitrate}}let o=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(l=>{let m=o.find(L=>L.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 _=0,g=0,R=0;m&&l.uint32_video_codec_bitrate>=m.uint32_video_codec_bitrate&&(_=m.uint32_video_codec_bitrate,g=m.uint32_video_enc_fps,R=m.uint32_video_codec_fps);let y=this.getDifferenceValue(_,l.uint32_video_codec_bitrate);l.uint32_video_codec_bitrate=Math.round(y*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(R,l.uint32_video_codec_fps)/s),ui&&Ut()===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),E(m.uint32_key_frame_count)||(l.uint32_key_frame_count=Math.round(this.getDifferenceValue(m.uint32_key_frame_count,l.uint32_key_frame_count))),E(m.uint32_nack_count)||(l.uint32_nack_count=Math.round(this.getDifferenceValue(m.uint32_nack_count,l.uint32_nack_count))),E(m.uint32_pli_count)||(l.uint32_pli_count=Math.round(this.getDifferenceValue(m.uint32_pli_count,l.uint32_pli_count))),E(m.uint32_video_arq_packets)||(l.uint32_video_arq_packets=Math.round(this.getDifferenceValue(m.uint32_video_arq_packets,l.uint32_video_arq_packets))),E(m.uint32_encode_cost)||(l.uint32_encode_cost=Math.round(this.getDifferenceValue(m.uint32_encode_cost,l.uint32_encode_cost)/s)),E(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=n.msg_down_stream_info;return e.msg_down_stream_info=e.msg_down_stream_info.filter(l=>c.find(m=>m.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid)),e.msg_down_stream_info.forEach(l=>{let m=c.find(_=>_.msg_user_info.uint64_tinyid===l.msg_user_info.uint64_tinyid);if(!Ct(l.msg_audio_status)&&!Ct(m.msg_audio_status)){let _=l.msg_audio_status,g=m.msg_audio_status,R=this.getDifferenceValue(g.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms_count);delete _.uint32_audio_cache_ms_count,_.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(g.uint32_audio_cache_ms,_.uint32_audio_cache_ms)/R)||0;let y=this.room.remotePublishedUserMap.get(l.msg_user_info.str_identifier);y&&(y.remoteAudioTrack.stat.jitterBufferDelay=_.uint32_audio_cache_ms),_.uint32_audio_origin_lost=this.getDifferenceValue(g.uint32_audio_origin_lost,_.uint32_audio_origin_lost),_.uint32_audio_receive=this.getDifferenceValue(g.uint32_audio_receive,_.uint32_audio_receive),_.uint32_audio_receive+=_.uint32_audio_origin_lost;let L=this.getDifferenceValue(g.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(L*8/s),_.uint32_audio_total_bitrate=Math.round(L*8/s)}else l.msg_audio_status={};if(l.msg_video_status&&m.msg_video_status){let _=m.msg_video_status;l.msg_video_status=l.msg_video_status.filter(R=>_.find(y=>y.uint32_video_stream_type===R.uint32_video_stream_type)),l.msg_video_status.forEach(R=>{let y=_.find(Yl=>Yl.uint32_video_stream_type===R.uint32_video_stream_type),L=y.uint32_video_receive,ie=y.uint32_video_origin_lost,W=y.uint32_video_codec_bitrate,en=y.uint32_video_receive_fps,Ql=y.uint32_video_dec_fps;R.uint32_video_origin_lost=this.getDifferenceValue(ie,R.uint32_video_origin_lost),R.uint32_video_receive=this.getDifferenceValue(L,R.uint32_video_receive)+R.uint32_video_origin_lost;let zl=this.getDifferenceValue(W,R.uint32_video_codec_bitrate);R.uint32_video_codec_bitrate=Math.round(zl*8/s);let ql=this.getDifferenceValue(en,R.uint32_video_receive_fps);R.uint32_video_receive_fps=Math.round(ql/s),R.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Ql,R.uint32_video_dec_fps)/s)})}}),e}getStatsReport(s){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let n={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_cache_ms:0,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}}]},o=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(n))),this.prepareReport({stats:o,report:n,freezeMap:t}),this._prevReportTime=Date.now(),n})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var Ol=ve(Ve());var id=class extends Ol.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"_uplinkRTT",0);u(this,"_uplinkLoss",0);u(this,"_downlinkRTT",0);u(this,"_downlinkLoss",0);u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(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(U.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(le.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;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=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=t.expectAudPkg+t.expectVidPkg,o=t.recvAudPkg+t.recvVidPkg,a=n-o;n===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/n*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)===se.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:d,totalPacketsLost:l,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m});continue}let _=0,g=this._downlinkPrevStatMap.get(c),R=l-g.totalPacketsLost,y=m-g.totalPacketsReceived;R<=0||y<0?_=0:_=Math.round(R/(R+y)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:_,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:n,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=n,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,n)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!xi())return t;let s=e.getReceivers();try{for(let n=0;n<s.length;n++)(yield s[n].getStats()).forEach(c=>{c.type==="candidate-pair"&&re(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(n){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==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="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===se.DISCONNECTED||e.connectionState===se.FAILED||e.connectionState===se.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(ht,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(f.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(id.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:n,audioDelay:o})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:n,audioDelay:o})}})}},Ji=id;u(Ji,"EVENT_NETWORK_QUALITY","0");function $p({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return hs(t)?t.catch(s=>A.error(`${r.name}() error observed ${s}`)):t}catch(t){A.error(`${r.name}() error observed ${t}`)}}}var Do=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};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")&&Q(this[e])&&(this[e]=$p({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=Z.run(ht,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:Te,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,as().then(i=>{this._basicInfo.string_os_version=cs(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),T.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(f.JOIN_START,this.handleJoinStart).addEvent(f.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(f.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(f.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(f.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(f.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(f.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(f.JOIN_FAILED,this.handleJoinFailed).addEvent(f.LEAVE_START,this.handleLeaveStart).addEvent(f.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(f.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(f.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(f.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(f.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(f.PUBLISH_START,this.handlePublishStart).addEvent(f.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(f.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(f.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(f.PLAY_TRACK_START,this.handlePlayStart).addEvent(f.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(f.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!pi(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(f.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(f.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(f.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(f.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,n=e.hasAuxiliary,o=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&o&&this.handleRemoteStreamAdded(t.userId,"main"),!n&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(f.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)=>T.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&&(E(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),E(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),E(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:n,tcp:o,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}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()):S.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 n={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({},Hp),{msg_user_info:new Xs({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};n.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,n)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:n,tinyId:o,role:a}=e,c=new Xs({userId:n,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),l=`${n}_${t}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=d),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:n,sendSubscribeCMDTime:d}),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:n,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,n=this._remoteStreamStatMap.get(s);n&&n.subscribedTime===0&&(n.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!pi(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(!pi(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),n=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),n)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&n){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-o.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:n,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,m;n&&(d=n,l=1),o&&(c=o,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,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:n,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:s}=e.msg_audio_status;Math.floor(s/it*100)>0&&(this._localStreamStat.totalAudioLevel+=s/it,this._localStreamStat.audioLevelCount++)}t.forEach(s=>{let{msg_user_info:n,msg_audio_status:o,msg_video_status:a}=s,c=n.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(l=>{let m=l.uint32_video_stream_type===2,_=l.uint32_video_stream_type===7,g=`${c}_${m?"main":"auxiliary"}`,R=this._remoteStreamStatMap.get(g);if(!!R&&(m&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||_&&(d==null?void 0:d.remoteAuxiliaryTrack))){R.totalVideoFPS+=l.uint32_video_receive_fps,R.totalVideoBitrate+=l.uint32_video_codec_bitrate,R.videoCount++,R.statsToReport.uint32_video_width===0&&(R.statsToReport.uint32_video_width=l.uint32_video_width),R.statsToReport.uint32_video_height===0&&(R.statsToReport.uint32_video_height=l.uint32_video_height);let y=m?d.remoteVideoTrack:d.remoteAuxiliaryTrack;y.stat.jitterBufferDelay&&(R.videoJitterBufferDelay=y.stat.jitterBufferDelay),y.stat.framesReceived&&(R.statsToReport.uint32_video_consume_render_rate=Math.floor(y.stat.framesDecoded/y.stat.framesReceived*Ur(10,6)))}}),o){let l=`${c}_${"main"}`,m=this._remoteStreamStatMap.get(l);this._remoteStreamStatMap.has(l)&&m&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(m.totalAudioBitrate+=o.uint32_audio_codec_bitrate,m.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/it*100)>0&&(m.totalAudioLevel+=o.uint32_audio_level/it,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():S.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())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&oi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ai)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Ni)>=0}hitTest(i){return i===this._room}checkStorage(){return p(this,null,function*(){try{let i=Ft.getItem(this._storageKey);i&&(yield this.upload(i),Ft.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&&Ft.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:_,videoDelayCount:g,totalAudioDelay:R,totalVideoDelay:y}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/m),_&&R&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/_),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),g&&y&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/g))}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:n}=this._room;n&&(i.statsToReport.uint32_audio_play_time=n.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=n.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,ji);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.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(d,i.statsToReport.uint32_video_play_time),o.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>ji&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+ji)}),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>ji&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+ji)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>ji&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+ji)}getReportData(){this._basicInfo.uint32_networkType=mr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Xs({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:ps(this._signalInfo.relayIp),uint32_client_ip:ps(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Ur(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:ps(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return wn(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),Ft.deleteItem(this._storageKey),this.initData()}catch(i){this._log.warn(i)}})}upload(i){return p(this,null,function*(){if(ot&&!ma||i.msg_path_enter_room.uint64_start_time===0||[nn,jo,Ko].findIndex(a=>a===location.host)>=0)return;let e=Number(this._room.sdkAppId),t=yield oa(i),s=t instanceof ArrayBuffer,n=`${hi(e,ni.KEY_POINT)}&gzip=${+s}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,t)),o||Vt({url:n,body:t}),this.uploadKVStat(P),this.uploadKVStat(wi)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=M(N({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield oa(e),s=`${hi(+this._room.sdkAppId,ni.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Vt({url:s,body:t})})}};b([Ri({settings:{timeout:500,retries:3}})],Do.prototype,"upload",1);var ji=5e3,Hp={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},Xs=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Dl=Do;var rd=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=B())}stop(){this._endTime===0&&(this._endTime=B())}getDuration(){return this._endTime===0?B()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Lr=rd;var sd=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(f.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(f.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(f.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var o;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 n=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(s);!n||(!e.hasAudio&&t.hasAudio&&n.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&n.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let o=new Lr,a=this._durationMap.get(n);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[o],video:[]})}else this.stopDurationItem(n,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let o=new Lr,a=this._durationMap.get(n);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[],video:[o]})}else this.stopDurationItem(n,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDurationItem(n,h.AUDIO),this.stopDurationItem(n,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,n=new Lr,o=this._durationMap.get(s);o?this.isRecording(o[e])||o[e].push(n):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[n]:[],video:e===h.AUDIO?[]:[n]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(n=>n.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,n)=>s+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},kl=sd;var nd=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(f.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(f.PLAY_TRACK_START,this.onPlayTrackStart).set(f.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDataFreeze({key:n,userId:s,type:e})}).set(f.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 n="main",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}if(e.hasAuxiliary&&!t.hasAuxiliary){let n="auxiliary",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}}).set(f.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!pi(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let n=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(n,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(f.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.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}`,n=this._dataFreezeMap.get(s),o=new Lr;n?n.durationItemList.push(o):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[o],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:n,muteState:o}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:n,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 n=s.durationItemList[s.durationItemList.length-1];n.stop();let o=n.getDuration();o>mn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:o}):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 n=`${i}_${t}`,o=this._renderFreezeMap.get(n);if(e<=2){let a=B();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(n,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=B();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!pi(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()<mn&&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 n=B(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=n-o.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()}},Ml=nd;var Ll=ve(Ve(),1);var Fp=[-1,-1,1,-1,-1,1,1,1],Gp=[0,0,1,0,0,1,1,1],Je=class extends w{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"image");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,e instanceof je){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),n=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;n.width=this.width,n.height=this.height,this.ctx2d=n.getContext("2d"),this.image=n,this._canvas=n}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(Gp),this.positionBuffer=this.createBuffer(Fp),t.createTexture!==!1&&(this.texture=s.createTexture(),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),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),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=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}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){let t=Date.now();if(this.context instanceof Ie&&this.render(e)||this.context instanceof je&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!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 e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Ie){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,n)=>{s&&(t.activeTexture(t.TEXTURE0+n),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,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.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,n)=>{t.enableVertexAttribArray(n),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(n,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.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;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)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,n,o){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,n,o),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:n,height:o,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:n,height:o,timestamp:d,fps:l,name:a,cost:c},N({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([oe(w.INIT,"connected",{sync:!0})],Je.prototype,"connect",1),b([oe("connected",w.INIT,{ignoreError:!0,sync:!0})],Je.prototype,"disconnect",1),b([oe([],"closed",{sync:!0})],Je.prototype,"close",1);var Wp=[0,1,1,1,0,0,1,0],Qs=class extends Je{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof je?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Wp)}start(e){this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Ie){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},xr=class extends Qs{constructor(e,t){super(e,t);u(this,"_videoTrack");[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let s=n=>{var c;let o=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(n,a)},a=()=>{o(),this.context.destroy(new Error(`video track ${n}`))};this.once("closed",o),(c=this._videoTrack)==null||c.addEventListener(n,a)};e instanceof Ie&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack}},ko=class extends xr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Mo=class extends xr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,n=e*t,o=this.resolution.width*this.resolution.height;A.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),n>o?s=n/o:(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=n/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var zs=class extends Je{constructor(e,t,s){super(e,N({name:"imageSource"},s));this.image=t;u(this,"_image");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(s==null?void 0:s.autoResize)!==!1}_render(e,t){let{width:s,height:n}=this;if(this.image instanceof HTMLVideoElement){if(Q(this.image.getVideoPlaybackQuality)&&!li){let a=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===a)return!1;this._totalFrames=a,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:s,videoHeight:n}=this.image),this.image.width=s,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:n}=this.image,this.image!==this._image)this._image=this.image;else if(s===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:n}=this.image,this._image=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===n&&this.totalFrames){if(t){this.useTexture();let o=this.context.ctx;o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,this.image)}this.resize(s,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Pr=class extends zs{constructor(e,t,s){let n=document.createElement("video");n.setAttribute("playsinline","playsinline"),n.setAttribute("muted","");super(e,n,s);this._videoTrack=t;u(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(){var e;super.close(),(e=this._mediaStream)==null||e.removeTrack(this._videoTrack),delete this._mediaStream,this.image.srcObject=null}};var Jp=`
|
|
115
44
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
116
45
|
attribute vec4 a_position;
|
|
117
46
|
attribute vec2 a_texCoord;
|
|
@@ -121,7 +50,7 @@ void main() {
|
|
|
121
50
|
gl_Position = a_position;
|
|
122
51
|
v_texCoord = a_texCoord;
|
|
123
52
|
}
|
|
124
|
-
`,
|
|
53
|
+
`,jp=`
|
|
125
54
|
// \u7247\u5143\u7740\u8272\u5668
|
|
126
55
|
precision mediump float;
|
|
127
56
|
varying vec2 v_texCoord;
|
|
@@ -129,14 +58,14 @@ uniform sampler2D u_texture;
|
|
|
129
58
|
|
|
130
59
|
void main() {
|
|
131
60
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
132
|
-
} `,
|
|
61
|
+
} `,Lo=class extends w{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e){return new Pr(this,e)}createVideoTrackDestination(e){return new xr(this,e)}createVideoImageSource(e,t){return new zs(this,e,t)}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}},Kp={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Ie=class extends Lo{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",Kp),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Jp),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,jp),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Error("webgl context lost"))}),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,n=s.createShader(e);return s.shaderSource(n,t),s.compileShader(n),n}createProgram(e,t){let s=this.ctx,n=s.createProgram();return s.attachShader(n,e),s.attachShader(n,t),s.linkProgram(n),s.getProgramParameter(n,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(n)),n}};b([oe(w.INIT,"created",{sync:!0})],Ie.prototype,"create",1),b([oe("created",w.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],Ie.prototype,"destroy",1);var je=class extends Lo{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};b([oe(w.INIT,"created",{sync:!0})],je.prototype,"create",1),b([oe("created",w.INIT,{ignoreError:!0,sync:!0})],je.prototype,"destroy",1);var Xp=[1,0,0,0,1,1,0,1],xo=class extends Je{constructor(i){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),i instanceof Ie)try{this.setTexBuffer(Xp)}catch(e){i.destroy(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(),this.draw(),!0):!1}};var od=class{constructor(i,e){this.node=i;this.layout=e;u(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}},Po=class extends Je{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0});u(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let s=new od(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((n,o)=>o?Object.assign(n,{width:Math.max(n.width,o.right),height:Math.max(n.height,o.bottom)}):n,{width:0,height:0});super.resize(s.width,s.height),this.context instanceof Ie&&this.inputs.forEach(n=>{if(n){let o=this.layout2texCoords(n);n.positionBuffer?this.changeBufferData(n.positionBuffer,o):n.positionBuffer=this.createBuffer(o)}})}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.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((n,o)=>(!o||!o.node.requestFrame(e))&&n,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let n=0;n<this.inputs.length;n++){let o=this.inputs[n];o&&(o.node.useTexture(),this.draw(o.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((s,n)=>(!n||!n.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 n=this.inputs[s];n&&this.draw2d(n.node.image,n.x,n.y,n.width,n.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:n,height:o,name:a}=this,c=Date.now(),d=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:n,height:o,timestamp:c,fps:d,name:a},N({parent:this.inputs.filter(l=>l).map(l=>l.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,s;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof Ie))try{(s=this.context.ctx)==null||s.deleteBuffer(e.positionBuffer)}catch(n){}})}};var Qp=`#version 300 es
|
|
133
62
|
in vec2 a_position;
|
|
134
63
|
in vec2 a_texCoord;
|
|
135
64
|
out vec2 v_texCoord;
|
|
136
65
|
void main() {
|
|
137
66
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
138
67
|
v_texCoord = a_texCoord;
|
|
139
|
-
}`,
|
|
68
|
+
}`,zp=`#version 300 es
|
|
140
69
|
precision highp float;
|
|
141
70
|
uniform sampler2D u_texture;
|
|
142
71
|
uniform sampler2D mask;
|
|
@@ -145,8 +74,9 @@ in vec2 v_texCoord;
|
|
|
145
74
|
out vec4 outColor;
|
|
146
75
|
void main() {
|
|
147
76
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
148
|
-
}`,Po=class extends Ur{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0});u(this,"ready",!1);u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return p(this,null,function*(){let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:n,y:o,width:a,height:c}=e.waterMark;this.wasm.setWaterMark(n,o,a,c)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let n=this.context.createShader(s.FRAGMENT_SHADER,e_),o=this.context.createShader(s.VERTEX_SHADER,Zp);this._prePrograme=this.context.createProgram(o,n),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){let t=this.context.ctx;if(typeof this.image.getVideoPlaybackQuality=="function"&&!ai){let c=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===c)return!1;this._totalFrames=c,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:n}=this.image;this.image.width=s,this.image.height=n;let o=!1;if(this.totalFrames)this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;o=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!o?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._selfieSegmentation.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)),this._selfieSegmentation.send(s,n)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var wo=class extends Pl.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"virtualBackgroundInstance");u(this,"isUsingArTrack",!1);u(this,"_bgAssetPath");u(this,"log",A.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new je({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ae({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=Z.run(Li,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(ai||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?B.addFailedEvent({key:s,error:t}):B.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var c;let t=this.cameraTrack,{small:s,settings:n,player:o}=t;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new ko(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=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),ai&&o.setCanvas(e);let a=e&&((c=this.destination)==null?void 0:c.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),t.setOutputMediaStreamTrack(a)}update(){return p(this,null,function*(){var s,n;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._selfieSegmentation?(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(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new Do(this.videoContext,{name:"mainDestination"})),this.cameraNode=new Po(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let o=this.cameraNode;o.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Lo(this.videoContext)),o=o.connect(this.mirrorNode),o.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new xo(this.videoContext),o.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),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._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),(n=this.screenNode)==null||n.connect(this.mixNode,{zIndex:0}),o=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),o.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)})}changeInput(e){if(this.log.info("change input"),e instanceof Ge)return this.setScreenTrack(e);if(e instanceof ae)return this.setCameraTrack(e);if(e instanceof Ot){let t=e.mediaTrack;if(ts===17&&+pt.split(".")[1]<4&&!e.source&&e.player.element){let s=new je({frameRate:15,logger:this.log,name:e.userId});s.create({alpha:!1});let n=s.createVideoImageSource(e.player.element);e.source=n;let o=new Ys(s);n.connect(o),e.player.setCanvas(s._canvas)}return e.setOutputMediaStreamTrack(t)}}removeInput(e){var t;e instanceof Ge?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ae?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Ot&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return p(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let n=s.getContext("2d");if(!n)throw new N({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((o,a)=>o.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:o,x:a,y:c,width:d,height:l})=>{n.drawImage(o,a,c,d,l)}),gs(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(n=>n.imageUrl===e.imageUrl&&n.height===e.height&&n.width===e.width&&n.x===e.x&&n.y===e.y&&n.type===e.type&&n.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(n=>n.type!==t)),this.watermarkImageList.push(e))}setWatermark(e){return p(this,null,function*(){let t;try{t=yield gs((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new N({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:n=0,width:o=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:n,width:o,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return p(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var t,s,n;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(n=this.cameraTrack)==null?void 0:n.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return p(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield gs(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} visual background, ${(e==null?void 0:e.type)||""}`),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=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,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.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}};var t_=0;var Vo=class extends P{constructor(e){super("room");this.seq=++t_;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,ue(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ue(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ue(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Ml({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Ll({room:this}),this.badCaseDetector=new xl({room:this}),this.audioManager=new io(this),this.videoManager=new wo(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 isJoining(){return this.state.toString()==="joining"}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(z(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if($e(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:n,scheduleProxy:o,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Sa([a,a]),Oi(`https://${a}`)):(n&&Oi(n),o&&Sa(o))}g.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:_i.main,sched_back_domain:_i.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}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 n=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=n.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new N({code:S.INVALID_OPERATION,message:O({key:v.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ee.INVALID_DESTROY),new N({code:S.INVALID_OPERATION,message:O({key:v.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,g.emit(f.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var n,o;let s=U();try{let{isCached:a,result:c,detailCost:d}=yield Vd({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:Se,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${dt(c,{keysToExclude:["username","credential"]})}`),a&&g.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=y(y({},this.scheduleResult),c),ee((n=c.config)==null?void 0:n.retryCount)&&ua(c.config.retryCount),z((o=c.config)==null?void 0:o.loggerDomain)&&Oi(c.config.loggerDomain),g.emit(f.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),B.addSuccessEvent({key:521700,cost:U()-s,split:50})}catch(a){throw B.addFailedEvent({key:521700,error:a}),a}})}};var Fl=ve(Ue());var ad=ve(Yc()),wl=r=>{let i=ce(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 n;if(t.ssrcs&&!E(t.ssrcs[0].id)){let o=Number(t.ssrcs[0].id),a=Number((n=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:n.id);switch(s){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e},Vl=(r,i)=>{var a,c;let e=ce(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],n=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),n.ext&&(t.video.extensions=n.ext.map(d=>({id:d.value,uri:d.uri})));let o={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:d,type:l,subtype:m})=>{if(d===o.payload){let _={id:l,params:[]};m&&_.params.push(m),o.rtcpFb.push(_)}}),t.audio.codecs.push(o);for(let d=0;d<n.rtp.length;d++){if(["rtx","red","ulpfec"].includes(n.rtp[d].codec))continue;let l=n.fmtp.filter(m=>m.payload===n.rtp[d].payload)[0];t.video.codecs.push({payload:n.rtp[d].payload,codec:n.rtp[d].codec,fmtp:l?l.config:"",rate:n.rtp[d].rate,rtx:((c=n.rtp[d+1])==null?void 0:c.codec)==="rtx"?n.rtp[d+1].payload:0,rtcpFb:((n==null?void 0:n.rtcpFb)||[]).filter(m=>m.payload===n.rtp[d].payload).map(({type:m,subtype:_})=>({id:m,params:_?[_]:[]}))})}return t},Ul=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),n={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},o={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 n.media.push(o),[1,2,3].forEach(a=>{n.media.push(cd({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&n.media.push(s.media.find(a=>a.mid==="dc")),qe(n)},cd=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,useAllCodec:s=!1})=>{let n={candidates:i.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(o=>({value:o.id,uri:o.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 o=0;o<i.video.codecs.length;o++)Uo(n,i.video.codecs[o]);else{let o=i.video.codecs.findIndex(a=>a.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));Uo(n,i.video.codecs[o])}else if(s)for(let o=0;o<e.video.codecs.length;o++)Uo(n,e.video.codecs[o]);else Uo(n,e.video.codecs[0]);return n.payloads=n.payloads.trim(),n},Uo=(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 i_(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 r_(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 s_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function n_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Bl=r=>{let i=ad.default.parse(r);return i.media.forEach(e=>{var t;(e.type===h.AUDIO||e.type===h.VIDEO)&&(r_(e),s_(e),n_(e),i_(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")}),ad.default.write(i)};var Zs=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 o=i;o<=e;o++){let a=this.dataView.getInt8(o);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 n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let o=i;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:s++,t.push(this.dataView.getInt8(o));break;case 3:s!==2&&t.push(this.dataView.getInt8(o)),s=0;break;default:t.push(this.dataView.getInt8(o)),s=0;break}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}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 n=6;n<this.dataView.buffer.byteLength;n++){let o=this.dataView.getUint8(n);if(e++,o===255)i+=255;else{i+=o;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let n=0;n<t.byteLength;n++,e++)s.setInt8(n,this.dataView.getInt8(e));return s}};var dd=class{constructor(i,e){this._singlePC=i;this._log=e;u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243);u(this,"_seiAbortMap",new Map);u(this,"_nonSeiAbortMap",new Map);u(this,"onSEIMessage",null)}isRunning(i){return this._seiAbortMap.has(i)}start(i){let e=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY,t=(e?i.sender:i.receiver).createEncodedStreams(),s=t.readable,n=t.writable,o=new TransformStream({transform:e?(c,d)=>this.encodeVideoFrame(c,d,i):(c,d)=>this.decodeVideoFrame(c,d,i)}),a=new AbortController;s.pipeThrough(o).pipeTo(n,a).catch(c=>{c!=="destroy"&&this._log.warn(c)}),this._seiAbortMap.set(i,a)}restart(i){this.stop(i),this.start(i)}stop(i){var e;(e=this._seiAbortMap.get(i))==null||e.abort(),this._seiAbortMap.delete(i)}destroy(){this._seiAbortMap.forEach(i=>i.abort("destroy")),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach(i=>i.abort("destroy")),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach((e,t)=>{var s,n;if(!(e.direction==="inactive"||!e.mid))if(t<4)t===1||t===2?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let o=(t-4)%3===1,a=(t-4)%3===2;((n=(s=e.receiver)==null?void 0:s.track)==null?void 0:n.kind)===h.VIDEO&&(o||a)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}})}catch(i){this._log.warn(i)}}pipeSenderOrReceiver(i){let t=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY?i.sender:i.receiver,{readable:s,writable:n}=t.createEncodedStreams(),o=new AbortController;this._nonSeiAbortMap.set(i,o),s.pipeTo(n,o).catch(()=>{})}push(i,e){var s,n;e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),((n=(s=this._singlePC.getPeerConnection())==null?void 0:s.getSenders()[2])==null?void 0:n.track)&&this._smallSeiMessageList.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 n=0;n<i.byteLength;n++)switch(s.getUint8(n)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encodeVideoFrame(i,e,t){try{let s=Number(t.mid)===2?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&s.length>0&&!this.isEmptyFrame(i)){let n=this.getNaluCount(i.data),o=9-n;if(o<=0)return;let a=s.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),c=a.reduce((T,C)=>T+C.dataView.byteLength,0),d=new ArrayBuffer(c+i.data.byteLength),l=new DataView(d),m=new DataView(i.data),_=0;for(let T=0;T<a.length;T++)for(let C=0;C<a[T].dataView.byteLength;C++)l.setInt8(_++,a[T].dataView.getInt8(C));for(let T=0;T<i.data.byteLength;T++)l.setInt8(_++,m.getInt8(T));i.data=d,this._log.debug(`${a.length} sei sent`)}}catch(s){this._log.warn(s)}e.enqueue(i)}decodeVideoFrame(i,e,t){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(i)&&this.hasSEI(i.data)){let s=[],n=new DataView(i.data),o=0,a=-1,c=-1;for(let d=0;d<i.data.byteLength;d++){let l=n.getUint8(d);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=d-o;if(a===-1?a=m:c===-1&&(c=m,s.push(new Zs(new DataView(n.buffer.slice(a,c)))),a=m,c=-1),!(n.getUint8(d+1)===6)){i.data=new DataView(n.buffer.slice(m)).buffer;break}}o=0}else o=0}this._log.debug(`${s.length} sei received`),Q(this.onSEIMessage)&&s.reverse().forEach(d=>{let l=Number(t.mid);this.onSEIMessage({seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,mid:l,streamType:(l-4)%3===2?"auxiliary":"main"})})}}catch(s){this._log.warn(s)}e.enqueue(i)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)n.push(255);n.push(s);let o=new DataView(i);return n.push(...new Uint8Array(o.buffer)),n.push(128),new Zs(new DataView(new Uint8Array(n).buffer),!0)}},$l=dd;var Lt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(Lt||{}),Gl=0,Wl=!1,o_=new Set,a_=r=>Gl>2&&!Wl&&o_.size===0&&r,c_=1,Qi=class extends Fl.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"_clientAbility",null);u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"_waitForPCConnectedPromiseReject",null);u(this,"_isSDPLogged",!1);u(this,"seiCodec",null);u(this,"enableInsertableStreams",!1);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${c_++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Vi&&(this.enableInsertableStreams=!0,this._log.info("create sei codec"),this.seiCodec=new $l(this,this._log),this.seiCodec.onSEIMessage=n=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(n.mid),data:n.data,seiPayloadType:n.seiPayloadType,streamType:n.streamType})})}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 videoCodec(){var e;return(e=this._serverAbility)!=null&&e.useVp8?"vp8":"h264"}get isUsingH264(){return this.videoCodec==="h264"}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?wl(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({encodedInsertableStreams:this.enableInsertableStreams,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 ld(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=Vl(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*(){var s;try{if(this.currentState==="CONNECTED")return;let n=U(),o={type:"answer",sdp:Ul({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||B.addSuccessEvent({key:521703,cost:U()-n}),(s=this.seiCodec)==null||s.handleEncodedStreams()}catch(n){let o=n instanceof N&&n.code===S.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${n}`,e),this.reset(),!o&&!this.isReconnecting&&(B.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}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(le.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:X.REBUILD_PEER_CONNECTION,responseCommand:V.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new N({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),B.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),g.emit(f.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=It(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==null?void 0:e.code} ${e}`),B.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Ft()&&this._log.warn(`SDK has tried reconnect for ${Ft()} 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._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(le.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===se.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===se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===se.FAILED||e.target.connectionState===se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===se.CONNECTED||e.target.connectionState===se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),g.emit(f.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 st;let e=null;return!Sr()||this._peerConnection.getSenders().length===0?st:(e=this._peerConnection.getSenders()[0].transport,!wi()||this._peerConnection.getReceivers().length===0?st:e?e.state:st)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Lt.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(Ti(s)){let n=e.get(s.localCandidateId),o=e.get(s.remoteCandidateId);n&&(this._log.info(`local candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port} ${n.networkType||""} ${n.candidateType==="relay"?`relayProtocol:${n.relayProtocol}`:""}`),n.networkType&&Aa(n.networkType)),o&&this._log.info(`remote candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.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),o(),e())},n=({room:c})=>{c===this._room&&(clearTimeout(a),o(),t(new N({code:S.API_CALL_ABORTED,message:O({key:v.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{g.off(f.LEAVE_SUCCESS,n,this),this.off(Lt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{o();let c=new N({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Gl+=1,a_(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),Wl=!0,this.emit(Lt.FIREWALL_RESTRICTION)),t(c)},ds);g.on(f.LEAVE_SUCCESS,n,this),this.on(Lt.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*(){var t;if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),(t=this.seiCodec)==null||t.handleEncodedStreams(),this._log.info(`addDownlink(${e.userId}) done`)}catch(s){this._log.error(`addDownlink(${e.userId}) failed ${s}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let n=this._peerConnection.getTransceivers().filter(l=>l.direction==="inactive").slice(0,3).map(l=>(l.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(l.mid)));n.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=ce(this._peerConnection.remoteDescription.sdp));let o,a,c;if(n.length===3)o=this._parsedAnswer.media.find(l=>Number(l.mid)===Number(n[0])),a=this._parsedAnswer.media.find(l=>Number(l.mid)===Number(n[1])),c=this._parsedAnswer.media.find(l=>Number(l.mid)===Number(n[2]));else{o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let l=cd({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),useAllCodec:!0});a=JSON.parse(JSON.stringify(l)),c=JSON.parse(JSON.stringify(l)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c)}o.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,o.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 d=`${s}-aux`;c.ssrcs=[{id:e.auxiliary,attribute:"cname",value:d},{id:e.auxiliary,attribute:"msid",value:`${d} ${s}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${d} ${s}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${d} ${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(t,[o.mid,a.mid,c.mid]),this._downlinkMIDUserIDMap.set(o.mid,t),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t)}removeDownlink(e,t){return p(this,null,function*(){if(!this._downlinkMIDMap.has(t)||!this._peerConnection)return;this._log.info(`removeDownlink(${t}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let s=this._downlinkMIDMap.get(t),n=!1;this._peerConnection.getTransceivers().forEach(o=>{s!=null&&s.includes(Number(o.mid))&&(n=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{s!=null&&s.includes(Number(o.mid))&&(n=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&n&&(yield this.updateSDP()),this._downlinkMIDMap.delete(t),s==null||s.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${t}) done`)})}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:n,auxVideo:o}=e;try{if(ys()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],m;d===0&&t?m=t:d===1&&s?m=s:d===2&&n?m=n:d===3&&o&&(m=o),m&&(yield this.setSenderMaxBitrate(l,m))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),o&&a[3].track&&(c=this.setStartBitrate(3,o)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth${a}`)}})}setStartBitrate(e,t){var s,n;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),(n=this._parsedAnswer.media[e])!=null&&n.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}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:n}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=q?"TIAS":"AS";e&&(o.media[0].bandwidth=[{type:a,limit:q?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:q?e*1e3:e}]),t&&(o.media[1].bandwidth=[{type:a,limit:q?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:q?t*1e3:t}]),s&&(o.media[2].bandwidth=[{type:a,limit:q?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:q?s*1e3:s}]),n&&(o.media[3].bandwidth=[{type:a,limit:q?n*1e3:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:q?n*1e3:n}]);let c={type:"offer",sdp:qe(o)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=qe(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,n)=>p(this,null,function*(){var o,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,s()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((o=this._peerConnection.localDescription)==null?void 0:o.sdp)}
|
|
77
|
+
}`,wo=class extends Pr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0});u(this,"ready",!1);u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return p(this,null,function*(){let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:n,y:o,width:a,height:c}=e.waterMark;this.wasm.setWaterMark(n,o,a,c)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let n=this.context.createShader(s.FRAGMENT_SHADER,zp),o=this.context.createShader(s.VERTEX_SHADER,Qp);this._prePrograme=this.context.createProgram(o,n),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){let t=this.context.ctx;if(typeof this.image.getVideoPlaybackQuality=="function"&&!li){let c=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===c)return!1;this._totalFrames=c,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:n}=this.image;this.image.width=s,this.image.height=n;let o=!1;if(this.totalFrames)this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;o=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!o?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._selfieSegmentation.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)),this._selfieSegmentation.send(s,n)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Vo=class extends Ll.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"virtualBackgroundInstance");u(this,"isUsingArTrack",!1);u(this,"_bgAssetPath");u(this,"log",A.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new je({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ie({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=Z.run(Oi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(li||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?P.addFailedEvent({key:s,error:t}):P.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var c;let t=this.cameraTrack,{small:s,settings:n,player:o}=t;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Mo(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=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),li&&o.setCanvas(e);let a=e&&((c=this.destination)==null?void 0:c.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),t.setOutputMediaStreamTrack(a)}update(){return p(this,null,function*(){var s,n;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._selfieSegmentation?(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(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new ko(this.videoContext,{name:"mainDestination"})),this.cameraNode=new wo(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let o=this.cameraNode;o.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new xo(this.videoContext)),o=o.connect(this.mirrorNode),o.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Po(this.videoContext),o.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),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._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),(n=this.screenNode)==null||n.connect(this.mixNode,{zIndex:0}),o=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),o.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)})}changeInput(e){if(this.log.info("change input"),e instanceof Ge)return this.setScreenTrack(e);if(e instanceof ae)return this.setCameraTrack(e);if(e instanceof bt){let t=e.mediaTrack;if(os===17&&+_t.split(".")[1]<4&&!e.source&&e.player.element){let s=new je({frameRate:15,logger:this.log,name:e.userId});s.create({alpha:!1});let n=s.createVideoImageSource(e.player.element);e.source=n;let o=new Qs(s);n.connect(o),e.player.setCanvas(s._canvas)}return e.setOutputMediaStreamTrack(t)}}removeInput(e){var t;e instanceof Ge?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ae?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof bt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return p(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let n=s.getContext("2d");if(!n)throw new C({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((o,a)=>o.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:o,x:a,y:c,width:d,height:l})=>{n.drawImage(o,a,c,d,l)}),fs(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(n=>n.imageUrl===e.imageUrl&&n.height===e.height&&n.width===e.width&&n.x===e.x&&n.y===e.y&&n.type===e.type&&n.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(n=>n.type!==t)),this.watermarkImageList.push(e))}setWatermark(e){return p(this,null,function*(){let t;try{t=yield fs((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new C({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:n=0,width:o=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:n,width:o,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return p(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var t,s,n;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(n=this.cameraTrack)==null?void 0:n.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return p(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield fs(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} visual background, ${(e==null?void 0:e.type)||""}`),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=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,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.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}};var qp=0;var Uo=class extends w{constructor(e){super("room");this.seq=++qp;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,ue(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ue(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ue(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Dl({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new kl({room:this}),this.badCaseDetector=new Ml({room:this}),this.audioManager=new ro(this),this.videoManager=new Vo(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 isJoining(){return this.state.toString()==="joining"}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(z(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Be(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:n,scheduleProxy:o,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Aa([a,a]),yi(`https://${a}`)):(n&&yi(n),o&&Aa(o))}T.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:mi.main,sched_back_domain:mi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}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 n=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=n.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new C({code:S.INVALID_OPERATION,message:D({key:v.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ee.INVALID_DESTROY),new C({code:S.INVALID_OPERATION,message:D({key:v.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,T.emit(f.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var n,o;let s=B();try{let{isCached:a,result:c,detailCost:d}=yield Pd({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:Te,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${ct(c,{keysToExclude:["username","credential"]})}`),a&&T.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),re((n=c.config)==null?void 0:n.retryCount)&&ea(c.config.retryCount),z((o=c.config)==null?void 0:o.loggerDomain)&&yi(c.config.loggerDomain),T.emit(f.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),P.addSuccessEvent({key:521700,cost:B()-s,split:50})}catch(a){throw P.addFailedEvent({key:521700,error:a}),a}})}};var $l=ve(Ve());var ad=ve(qc()),xl=r=>{let i=ce(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 n;if(t.ssrcs&&!E(t.ssrcs[0].id)){let o=Number(t.ssrcs[0].id),a=Number((n=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:n.id);switch(s){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e},Pl=(r,i)=>{var a,c;let e=ce(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],n=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),n.ext&&(t.video.extensions=n.ext.map(d=>({id:d.value,uri:d.uri})));let o={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:d,type:l,subtype:m})=>{if(d===o.payload){let _={id:l,params:[]};m&&_.params.push(m),o.rtcpFb.push(_)}}),t.audio.codecs.push(o);for(let d=0;d<n.rtp.length;d++){if(["rtx","red","ulpfec"].includes(n.rtp[d].codec))continue;let l=n.fmtp.filter(m=>m.payload===n.rtp[d].payload)[0];t.video.codecs.push({payload:n.rtp[d].payload,codec:n.rtp[d].codec,fmtp:l?l.config:"",rate:n.rtp[d].rate,rtx:((c=n.rtp[d+1])==null?void 0:c.codec)==="rtx"?n.rtp[d+1].payload:0,rtcpFb:((n==null?void 0:n.rtcpFb)||[]).filter(m=>m.payload===n.rtp[d].payload).map(({type:m,subtype:_})=>({id:m,params:_?[_]:[]}))})}return t},wl=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),n={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},o={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 n.media.push(o),[1,2,3].forEach(a=>{n.media.push(cd({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&n.media.push(s.media.find(a=>a.mid==="dc")),Ye(n)},cd=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,useAllCodec:s=!1})=>{let n={candidates:i.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(o=>({value:o.id,uri:o.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 o=0;o<i.video.codecs.length;o++)Bo(n,i.video.codecs[o]);else{let o=i.video.codecs.findIndex(a=>a.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));Bo(n,i.video.codecs[o])}else if(s)for(let o=0;o<e.video.codecs.length;o++)Bo(n,e.video.codecs[o]);else Bo(n,e.video.codecs[0]);return n.payloads=n.payloads.trim(),n},Bo=(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 Yp(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 Zp(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 e_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function t_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Vl=r=>{let i=ad.default.parse(r);return i.media.forEach(e=>{var t;(e.type===h.AUDIO||e.type===h.VIDEO)&&(Zp(e),e_(e),t_(e),Yp(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")}),ad.default.write(i)};var qs=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 o=i;o<=e;o++){let a=this.dataView.getInt8(o);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 n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let o=i;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:s++,t.push(this.dataView.getInt8(o));break;case 3:s!==2&&t.push(this.dataView.getInt8(o)),s=0;break;default:t.push(this.dataView.getInt8(o)),s=0;break}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}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 n=6;n<this.dataView.buffer.byteLength;n++){let o=this.dataView.getUint8(n);if(e++,o===255)i+=255;else{i+=o;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let n=0;n<t.byteLength;n++,e++)s.setInt8(n,this.dataView.getInt8(e));return s}};var dd=class{constructor(i,e){this._singlePC=i;this._log=e;u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243);u(this,"_seiAbortMap",new Map);u(this,"_nonSeiAbortMap",new Map);u(this,"onSEIMessage",null)}isRunning(i){return this._seiAbortMap.has(i)}start(i){let e=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY,t=(e?i.sender:i.receiver).createEncodedStreams(),s=t.readable,n=t.writable,o=new TransformStream({transform:e?(c,d)=>this.encodeVideoFrame(c,d,i):(c,d)=>this.decodeVideoFrame(c,d,i)}),a=new AbortController;s.pipeThrough(o).pipeTo(n,a).catch(c=>{c!=="destroy"&&this._log.warn(c)}),this._seiAbortMap.set(i,a)}restart(i){this.stop(i),this.start(i)}stop(i){var e;(e=this._seiAbortMap.get(i))==null||e.abort(),this._seiAbortMap.delete(i)}destroy(){this._seiAbortMap.forEach(i=>i.abort("destroy")),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach(i=>i.abort("destroy")),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach((e,t)=>{var s,n;if(!(e.direction==="inactive"||!e.mid))if(t<4)t===1||t===2?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let o=(t-4)%3===1,a=(t-4)%3===2;((n=(s=e.receiver)==null?void 0:s.track)==null?void 0:n.kind)===h.VIDEO&&(o||a)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}})}catch(i){this._log.warn(i)}}pipeSenderOrReceiver(i){let t=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY?i.sender:i.receiver,{readable:s,writable:n}=t.createEncodedStreams(),o=new AbortController;this._nonSeiAbortMap.set(i,o),s.pipeTo(n,o).catch(()=>{})}push(i,e){var s,n;e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),((n=(s=this._singlePC.getPeerConnection())==null?void 0:s.getSenders()[2])==null?void 0:n.track)&&this._smallSeiMessageList.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 n=0;n<i.byteLength;n++)switch(s.getUint8(n)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encodeVideoFrame(i,e,t){try{let s=Number(t.mid)===2?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&s.length>0&&!this.isEmptyFrame(i)){let n=this.getNaluCount(i.data),o=9-n;if(o<=0)return;let a=s.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),c=a.reduce((g,R)=>g+R.dataView.byteLength,0),d=new ArrayBuffer(c+i.data.byteLength),l=new DataView(d),m=new DataView(i.data),_=0;for(let g=0;g<a.length;g++)for(let R=0;R<a[g].dataView.byteLength;R++)l.setInt8(_++,a[g].dataView.getInt8(R));for(let g=0;g<i.data.byteLength;g++)l.setInt8(_++,m.getInt8(g));i.data=d,this._log.debug(`${a.length} sei sent`)}}catch(s){this._log.warn(s)}e.enqueue(i)}decodeVideoFrame(i,e,t){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(i)&&this.hasSEI(i.data)){let s=[],n=new DataView(i.data),o=0,a=-1,c=-1;for(let d=0;d<i.data.byteLength;d++){let l=n.getUint8(d);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=d-o;if(a===-1?a=m:c===-1&&(c=m,s.push(new qs(new DataView(n.buffer.slice(a,c)))),a=m,c=-1),!(n.getUint8(d+1)===6)){i.data=new DataView(n.buffer.slice(m)).buffer;break}}o=0}else o=0}this._log.debug(`${s.length} sei received`),Q(this.onSEIMessage)&&s.reverse().forEach(d=>{let l=Number(t.mid);this.onSEIMessage({seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,mid:l,streamType:(l-4)%3===2?"auxiliary":"main"})})}}catch(s){this._log.warn(s)}e.enqueue(i)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)n.push(255);n.push(s);let o=new DataView(i);return n.push(...new Uint8Array(o.buffer)),n.push(128),new qs(new DataView(new Uint8Array(n).buffer),!0)}},Ul=dd;var kt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(kt||{}),Hl=0,Fl=!1,i_=new Set,r_=r=>Hl>2&&!Fl&&i_.size===0&&r,s_=1,si=class extends $l.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"clientAbility");u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"_waitForPCConnectedPromiseReject",null);u(this,"_isSDPLogged",!1);u(this,"seiCodec",null);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${s_++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Ei&&(this._log.info("create sei codec"),this.seiCodec=new Ul(this,this._log),this.seiCodec.onSEIMessage=n=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(n.mid),data:n.data,seiPayloadType:n.seiPayloadType,streamType:n.streamType})})}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 videoCodec(){var e;return(e=this._serverAbility)!=null&&e.useVp8?"vp8":"h264"}get isUsingH264(){return this.videoCodec==="h264"}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?xl(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*(){let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&Ei,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 ld(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}),e=yield this._peerConnection.createOffer(),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=Pl(e.sdp,this._enableCustomMessage),P.addSuccessEvent({key:521707}),this.clientAbility}catch(t){throw P.addFailedEvent({key:521707,error:t}),this._log.error(`initialize failed ${t}
|
|
78
|
+
offer: ${e==null?void 0:e.sdp}`),t}})}connect(e,t=!1){return p(this,null,function*(){var s;try{if(this.currentState==="CONNECTED")return;let n=B(),o={type:"answer",sdp:wl({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||P.addSuccessEvent({key:521703,cost:B()-n}),(s=this.seiCodec)==null||s.handleEncodedStreams()}catch(n){let o=n instanceof C&&n.code===S.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${n}`,e),this.reset(),!o&&!this.isReconnecting&&(P.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}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(le.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:X.REBUILD_PEER_CONNECTION,responseCommand:U.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new C({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),P.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(f.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=St(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==null?void 0:e.code} ${e}`),P.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=wt()&&this._log.warn(`SDK has tried reconnect for ${wt()} 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._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(le.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===se.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===se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===se.FAILED||e.target.connectionState===se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===se.CONNECTED||e.target.connectionState===se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(f.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 et;let e=null;return!fr()||this._peerConnection.getSenders().length===0?et:(e=this._peerConnection.getSenders()[0].transport,!xi()||this._peerConnection.getReceivers().length===0?et:e?e.state:et)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(kt.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(fi(s)){let n=e.get(s.localCandidateId),o=e.get(s.remoteCandidateId);n&&(this._log.info(`local candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port} ${n.networkType||""} ${n.candidateType==="relay"?`relayProtocol:${n.relayProtocol}`:""}`),n.networkType&&Ra(n.networkType)),o&&this._log.info(`remote candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.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),o(),e())},n=({room:c})=>{c===this._room&&(clearTimeout(a),o(),t(new C({code:S.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(f.LEAVE_SUCCESS,n,this),this.off(kt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{o();let c=new C({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Hl+=1,r_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Fl=!0,this.emit(kt.FIREWALL_RESTRICTION)),t(c)},Kr);T.on(f.LEAVE_SUCCESS,n,this),this.on(kt.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*(){var t;if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),(t=this.seiCodec)==null||t.handleEncodedStreams(),this._log.info(`addDownlink(${e.userId}) done`)}catch(s){this._log.error(`addDownlink(${e.userId}) failed ${s}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let n=this._peerConnection.getTransceivers().filter(_=>_.direction==="inactive").slice(0,3).map(_=>(_.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(_.mid)));this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let o=this._parsedAnswer.media.filter(_=>{var g;return(g=_.ssrcs)==null?void 0:g.find(R=>{var y;return(y=R.value)==null?void 0:y.includes(s)})}),a,c,d;if(o.length===3)a=o[0],c=o[1],d=o[2];else if(n.length===3)a=this._parsedAnswer.media.find(_=>Number(_.mid)===Number(n[0])),c=this._parsedAnswer.media.find(_=>Number(_.mid)===Number(n[1])),d=this._parsedAnswer.media.find(_=>Number(_.mid)===Number(n[2]));else if(n.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}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let _=cd({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),useAllCodec:!0});c=JSON.parse(JSON.stringify(_)),d=JSON.parse(JSON.stringify(_)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let l=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${l}`},{id:e.audio,attribute:"msid",value:`${l}-${h.MAIN} ${l}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${l}`},{id:e.video,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${l}`},{id:e.videoRtx,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${l}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(_=>_.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return p(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(n=>{t!=null&&t.includes(Number(n.mid))&&(s=!0,n.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(n=>{t!=null&&t.includes(Number(n.mid))&&(s=!0,n.direction="inactive",n.ssrcs=[],n.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(n=>this._downlinkMIDUserIDMap.delete(n)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:n,auxVideo:o}=e;try{if(As()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],m;d===0&&t?m=t:d===1&&s?m=s:d===2&&n?m=n:d===3&&o&&(m=o),m&&(yield this.setSenderMaxBitrate(l,m))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),o&&a[3].track&&(c=this.setStartBitrate(3,o)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var s,n;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),(n=this._parsedAnswer.media[e])!=null&&n.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}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:n}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=Y?"TIAS":"AS";e&&(o.media[0].bandwidth=[{type:a,limit:Y?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:Y?e*1e3:e}]),t&&(o.media[1].bandwidth=[{type:a,limit:Y?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:Y?t*1e3:t}]),s&&(o.media[2].bandwidth=[{type:a,limit:Y?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:Y?s*1e3:s}]),n&&(o.media[3].bandwidth=[{type:a,limit:Y?n*1e3:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:Y?n*1e3:n}]);let c={type:"offer",sdp:Ye(o)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=Ye(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,n)=>p(this,null,function*(){var o,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,s()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((o=this._peerConnection.localDescription)==null?void 0:o.sdp)}
|
|
149
79
|
next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
|
|
150
|
-
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:d,currentDirection:l,direction:m,stopped:_})=>({mid:d,currentDirection:l,direction:m,stopped:_})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,n(c)}})),this._updateSDPPromise}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:Bl(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.seiCodec&&(this.seiCodec.destroy(),this.seiCodec=null),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var s;(s=this.seiCodec)==null||s.push(e,t)}};b([to("reconnect")],Qi.prototype,"startReconnection",1),b([bt()],Qi.prototype,"updateSDP",1);var ud=class{constructor(i){u(this,"tag");u(this,"len");u(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}},ld=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let n=e.getUint16(t+2),o=new ud(new Uint8Array(i).slice(t,t+2+2+n).buffer);s.push(o),t+=2+2+n}s.forEach(n=>{n.tag===1?this.tinyId=new TextDecoder().decode(n.data):n.tag===2&&(this.data=n.data)})}},Hl=new Set;function Yi(){let r=Math.floor(Math.random()*4294967296);return Hl.has(r)?Yi():(Hl.add(r),r)}var Jl=ve(Ue());var qi=class extends Jl.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_currentState","DISCONNECTED");u(this,"_prevTime",-1);u(this,"_enableSEI");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}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)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(g.emit(f.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 hd=class extends qi{constructor(e){super(L(y({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(this,"_flag",0);u(this,"_checkPublishStateTimeoutId",-1);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:n,smallVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:n||0,smallRtx:o||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,n=Object.keys(t).find(o=>t[o]!==s[o]);if(n)if(e)this._log.warn(`publish state not matched, ${n} local:${t[n]} server:${s[n]} ${rs()}`),B.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Z.run(mi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Z.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(At()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.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}get serverPublishState(){return{audio:!!(this.flag&li),bigVideo:!!(this.flag&ui),smallVideo:!!(this.flag&as),auxVideo:!!(this.flag&Di)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack)}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 o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,m,_,T,C,R;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:o,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,o.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new N({code:S.NOT_SUPPORTED_H264,message:O({key:v.NOT_SUPPORTED_H264ENCODE})});ge&&Vt()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Xe["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(o.auxVideo=!0,a.auxVideo=t.muted):(o.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,o.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:X.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:L(y({},this.singlePC.uplinkSSRC),{state:o,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),(d=this.singlePC.seiCodec)==null||d.handleEncodedStreams(),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s)t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e);else{if(t){this.localMainVideoTrack=t;let{scaleResolutionDownBy:M}=t;M>1&&(this._log.warn(`setScaleResolutionDownBy main ${M}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[1],M))}e&&(this.localMainAudioTrack=e)}yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((m=this.localAuxAudioTrack)==null?void 0:m.profile.bitrate),bigVideo:(_=this.localMainVideoTrack)==null?void 0:_.profile.bitrate,smallVideo:(C=(T=this.localMainVideoTrack)==null?void 0:T.small)==null?void 0:C.bitrate,auxVideo:(R=this.localAuxVideoTrack)==null?void 0:R.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){if(!ze())return;this._log.info("publish by transceiver");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),d=[],l=[];if(a){let _=c[0].sender.replaceTrack(a);l.push(0),d.push(_)}if(o)if(n){let _=c[3].sender.replaceTrack(o);l.push(3),d.push(_)}else{let _=c[1].sender.replaceTrack(o);l.push(1),d.push(_)}if(s){let _=c[2].sender.replaceTrack(s);l.push(2),d.push(_)}let m=this.setTransceiverDirection(j.SENDONLY,l);return d.push(m),Promise.all(d)}enableSmall(e){return p(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(j.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(j.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}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 n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(y({},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=L(y({},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(j.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.sendWaitForResponseWithRetry({command:X.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Rt){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:X.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){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`),At()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===j.INACTIVE&&(yield this.setTransceiverDirection(j.SENDONLY,[o]))}for(let o=0;o<4;o++){let{readable:a,writable:c}=s[o].sender.createEncodedStreams();a.pipeTo(c)}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`),At()&&(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)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(j.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!q)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
151
|
-
`).map(d=>{if(d.match(new RegExp(`a=(${
|
|
152
|
-
`);n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return p(this,null,function*(){var o;let t=(o=this._peerConnection)==null?void 0:o.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${s.kind} track on ${n?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!n&&t[1]&&(yield t[1].replaceTrack(s)),n&&t[3]&&(yield t[3].replaceTrack(s)))})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let o={};t===h.AUDIO?o.audio=e:s==="big"?o.bigVideo=e:s==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:X.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(f.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===ki?(this._log.error(Ee.NOT_SUPPORTED_H264ENCODE),new N({code:S.NOT_SUPPORTED_H264,message:O({key:v.NOT_SUPPORTED_H264ENCODE})})):new N({code:S.UNKNOWN,message:O({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},md=hd;function jl(r){return Object.keys(r).filter(i=>r[i])}var en=class extends qi{constructor(e){super(L(y({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new Zt(this._room,this),this.remoteVideoTrack=new Ot(this._room,this),this.remoteAuxiliaryTrack=new Nr(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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 n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){var l;if((l=this.singlePC)!=null&&l.enableInsertableStreams){let{readable:m,writable:_}=e.receiver.createEncodedStreams();if(e.track.kind===h.VIDEO)m.pipeTo(_);else{let T=new AudioDecoder({error:R=>this._log.error(R),output:R=>{this.remoteAudioTrack.write(R)}});T.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info("audioDecoder state:"+T.state);let C=new TransformStream({transform:(R,M)=>p(this,null,function*(){T.decode(new EncodedAudioChunk({data:R.data,timestamp:R.timestamp,type:"key"})),M.enqueue(R)})});m.pipeThrough(C).pipeTo(_).then(()=>T.close()).catch(R=>{T.close(),this._log.error(R)});return}}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 d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),d.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} ${jl(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(n=>n===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new N({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,n;(e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting&&(this._log.warn("remote track ended start spc reconnect"),this.singlePC.startReconnection())}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 n=y({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${jl(n)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,n),o==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=X.UNSUBSCRIBE,o=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=X.SUBSCRIBE_CHANGE,o=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:s,responseCommand:o,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new N({code:a.code,message:O({key:v.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._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}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:Yi(),bigVideoSsrc:Yi(),bigVideoRtxSsrc:Yi(),auxVideoSsrc:Yi(),auxVideoRtxSsrc:Yi()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:n,video:o,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:X.SPC_SUBSCRIBE,responseCommand:V.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},retries:3,retryTimeout:0});if(l.data.code!==0)throw new N({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}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))})}};b([bt(),F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this.off("closed",s),t(new N({code:S.API_CALL_ABORTED,message:O({key:v.CONNECTION_ABORTED,data:n})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],en.prototype,"subscribe",1),b([bt()],en.prototype,"unsubscribe",1);var Kl=en;function Xl(){return F(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;g.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function zl(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var{isString:Ql,isPlainObject:WL,isUndefined:Br,getNetworkType:d_,getTerminalType:u_,isEmpty:tn}=De,xt=class extends Vo{constructor(e){super(e);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=Cs;this._changeBigSmallRecords=new Map;this._networkQuality=null;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 zs(this,this._log),this.userManager=new mo(this.userId,this._log),this._version=Se,this.sdpSemantics=lr,Br(e.sdpSemantics)?zt.isUnifiedPlanDefault()&&(this.sdpSemantics=hi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${d_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Br(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!Br(e.enableSPC)&&Cs&&(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",n=>{this.emit("peer-join",n)}),this.userManager.on("2",n=>{this.closeDownLinkConnection(n,"remote user exitRoom"),this.emit("peer-leave",n)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",o=>{var n=Ed(o,[]);g.emit(f.REMOTE_PUBLISH_STATE_CHANGED,y({room:this},n)),this.emit("remote-publish-state-changed",y({},n))}),this._joinOptions=e,new Promise((n,o)=>p(this,null,function*(){this._joinReject=o;try{this.checkDestroy();let[,a]=yield Promise.all([this.initialize(),this.initSinglePC()]);yield this.doJoin(e,a),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(a){o(a)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Qi({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){this.singlePC.close(),this.singlePC=null}}})}doJoin(e,t){return new Promise((s,n)=>p(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(le.SETUP_FAILED,m=>{this.clearJoinTimeout(),g.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),n(m)}),ue((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Cs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={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:u_(),netType:Er(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(o)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{n(new N({code:S.JOIN_ROOM_FAILED,message:O({key:v.JOIN_ROOM_TIMEOUT})}))},a),g.emit(f.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?X.SPC_JOIN_ROOM:X.JOIN_ROOM,o),this._signalChannel.once(V.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:_,message:T,data:C,tinyId:R}=m.data;g.emit(f.JOIN_RECEIVED_CMD_RES,{room:this,code:_}),_===0?(this._log.info("Join room success, start heartbeat"),R&&(this.tinyId=R),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=C.publishers,this.singlePC&&this.singlePC.connect(C.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${_} error: ${T}`),n(new N({code:S.JOIN_ROOM_FAILED,extraCode:_,message:O({key:v.JOIN_ROOM_FAILED,data:{error:T,code:_}})})))})}))}reJoin(e=!0){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(n=>(t=n,n)))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),s.push(this._signalChannel.connect())),yield Promise.all(s),yield this.doJoin(L(y({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey}),t),this._log.warn("reJoin success"),te.logSuccessEvent({userId:this.userId,eventType:Le.REJOIN}),this.singlePC){let n=o=>{var a;o.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Lt.CONNECTION_STATE_CHANGED,n),this.uplinkConnection instanceof md&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Lt.CONNECTION_STATE_CHANGED,n),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof vo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),te.logFailedEvent({userId:this.userId,eventType:Le.REJOIN,error:t}),this.emit("error",new N({code:S.JOIN_ROOM_FAILED,message:O({key:v.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this._signalChannel||Tl(this.userId),n=!!(s&&s.isConnected&&s.keepAlive);return this._log.info(`${n?"reuse":"setup"} signal channel`),n?(s.url=e,s.backupUrl=t,s.room=this,this._signalChannel=s):this._signalChannel=new xr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._networkQuality||(this._networkQuality=new Xi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Xi.EVENT_NETWORK_QUALITY,o=>{this.emit("network-quality",o)})),Pe(this,this._signalChannel).add(le.CONNECTION_STATE_CHANGED,o=>{g.emit(f.SIGNAL_CONNECTION_STATE_CHANGED,y({room:this},o)),this.emit("signal-connection-state-changed",o)}).add(le.RECONNECT_FAILED,o=>{this.reset(),this.emit("error",o)}).add(V.PEER_JOIN,o=>{let{srcTinyId:a,userId:c,role:d}=o.data.data;this.userManager.addUser({userId:c,tinyId:a,role:d})}).add(V.PEER_LEAVE,o=>{let{userId:a,reason:c=0}=o.data.data;this.userManager.deleteUser(a,c)}).add(V.UPDATE_REMOTE_MUTE_STAT,o=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(o.data)}).add(V.CLIENT_BANNED,o=>{let a=o.data.data,{reason:c}=a;if(te.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(le.SETUP_SUCCESS,o=>{this.tinyId=o.signalInfo.tinyId,g.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this})}),g.emit(f.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&g.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this._signalChannel=e,e||pe(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),g.emit(f.LEAVE_SEND_CMD,{room:this}),(e=this._signalChannel)==null||e.send(X.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(ft,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?Fu(this.userId):[],n=y({str_sdk_version:vi,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:Er()},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t);g.emit(f.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(X.ON_QUALITY_REPORT,n),this.emit("heartbeat-report",L(y({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:n,flag:o})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=o);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:n,flag:o}});g.emit(f.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 n=new(this.singlePC?Kl:Zc)({userId:e,tinyId:t,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}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("error",s=>{let n=s.getCode();n!==S.ICE_TRANSPORT_ERROR&&(n===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",L(y({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Z.run(ft,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:X.GET_USER_LIST,responseCommand:V.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:n}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw O({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.USER_LIST_RES,code:s,message:n}})}):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||!Xc)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(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof We&&!s.getIsReconnecting()){let n=s.getPeerConnection();n&&n.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),te.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,yield this.reJoin(!1),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new vo({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})),t.close()}this.remotePublishedUserMap.forEach(t=>{let s=new Zc({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 N({code:S.INVALID_OPERATION,message:O({key:v.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:X.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:V.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this._signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:n,message:o}=s.data;if(n!==0)throw new N({code:S.SWITCH_ROLE_FAILED,message:O({key:v.SWITCH_ROLE_FAILED,data:{message:o,code:n}})});this.role=e}).catch(s=>{throw s instanceof N&&s.getCode()===S.API_CALL_TIMEOUT&&(s=new N({code:S.SWITCH_ROLE_FAILED,message:O({key:v.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return p(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof ye&&(c instanceof vt?s.audio=c:t.audio=c),c instanceof ae&&(c instanceof Ge&&c.mediaType===2?s.video=c:t.video=c)});let n=tn(t),o=tn(s);(!n||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new md({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new vo({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",L(y({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==S.ICE_TRANSPORT_ERROR&&(d===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");n||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),o||(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(n=>{!n.mediaTrack||!n.isPublished||(n instanceof ye&&(n instanceof vt?s.audio=n:t.audio=n),n instanceof ae&&(n instanceof Ge&&n.mediaType===2?s.video=n:t.video=n))});try{let n=e.map(o=>o.kind).join(",");tn(t)||(this._log.info(`unpublish() => main ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),tn(s)||(this._log.info(`unpublish() => aux ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(n){}this.localTracks.size===0&&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||!Pa()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{g.emit(f.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(o=>!o.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=y({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 8:o.smallVideo=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),g.emit(f.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:s,subscribeState:o}),this._log.info(`subscribe() => ${t} ${n} [${bo(o)}] prev: [${bo(s.subscribeState)}]`),yield s.subscribe(o,n),this._log.info(`subscribe ${t} ${n} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());g.emit(f.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})}catch(o){let a=o instanceof N?o.getCode():S.UNKNOWN,c=o;throw o instanceof N?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new N({code:S.API_CALL_ABORTED,message:O({key:v.API_CALL_ABORTED,data:{message:o.message,userId:t,streamType:n}})}),this._log.warn(c)):(c=new N({code:a,message:O({key:v.SUBSCRIBE_FAILED,data:{message:o.message,userId:t,streamType:n}})}),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 n=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${n}`);try{yield s.unsubscribe({remoteTracks:e,streamType:n})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),g.emit(f.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,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)),g.emit(f.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run(ls,()=>{var n;let s=[];(n=this.remotePublishedUserMap)==null||n.forEach(o=>{if(o.muteState.hasAudio){let a=Math.floor(o.remoteAudioTrack.getAudioLevel()*100);s.push({userId:o.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:n,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,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,n]of this.remotePublishedUserMap)e==="main"&&n.muteState.hasVideo&&(t[s]=n.remoteVideoTrack.stat),e==="auxiliary"&&n.muteState.hasAuxiliary&&(t[s]=n.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(n=>s.push(De.getTurnServer(n))):De.isPlainObject(e)&&s.push(De.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:X.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:X.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?X.START_PUBLISH_TENCENT_CDN:X.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.START_PUBLISH_TENCENT_CDN_RES:V.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?X.STOP_PUBLISH_TENCENT_CDN:X.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this._signalChannel)==null||t.sendWaitForResponse({command:X.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.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=De.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{subscribeState:t,userId:s,muteState:{hasSmall:n,hasVideo:o}}=e;if(!n&&!o||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&n)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!n&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${hr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=hr}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${hr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let n={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:hr};this._changeBigSmallRecords.set(t.userId,n),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(Ql(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Br(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new N({code:S.INVALID_PARAMETER,message:O({key:v.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(!Br(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new N({code:S.INVALID_PARAMETER,message:O({key:v.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Br(e.userDefinePushArgs))if(Ql(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 N({code:S.INVALID_PARAMETER,message:O({key:v.INVALID_USER_DEFINE_PUSH_ARGS})});tn(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}code3(){if(this.singlePC)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}};b([Jc(["left",ie.INIT],"joined"),yi({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),St(!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))}}),ll()],xt.prototype,"join",1),b([Jc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),hl(),to("leave room"),Js({fnName:"publish",validateArgs:!1}),Js({fnName:"unsubscribe",validateArgs:!1})],xt.prototype,"leave",1),b([bt(),Xl(),yi({settings:{retries:Ft,timeout:r=>It(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),g.emit(f.PUBLISH_FAILED,{room:this}))}})],xt.prototype,"publish",1),b([Js({fnName:"publish"}),xu("api-call"),bt(),zl()],xt.prototype,"unpublish",1),b([Za((...r)=>r[0].userId),ro(),ml(),yi({settings:{retries:Ft,timeout:r=>It(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),g.emit(f.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],xt.prototype,"subscribe",1),b([Js({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")})}}),Za((...r)=>r[0].userId)],xt.prototype,"unsubscribe",1);Hs.create=Hs._create.bind(Hs,xt);var QL=Hs;export{QL as default};
|
|
80
|
+
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:d,currentDirection:l,direction:m,stopped:_})=>({mid:d,currentDirection:l,direction:m,stopped:_})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,n(c)}})),this._updateSDPPromise}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:Vl(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.seiCodec&&(this.seiCodec.destroy(),this.seiCodec=null),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var s;(s=this.seiCodec)==null||s.push(e,t)}};b([io("reconnect")],si.prototype,"startReconnection",1),b([Ar(r=>r.userId)],si.prototype,"addDownlink",1),b([Ar(r=>r)],si.prototype,"removeDownlink",1),b([yt(!0)],si.prototype,"updateSDP",1);var ud=class{constructor(i){u(this,"tag");u(this,"len");u(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}},ld=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let n=e.getUint16(t+2),o=new ud(new Uint8Array(i).slice(t,t+2+2+n).buffer);s.push(o),t+=2+2+n}s.forEach(n=>{n.tag===1?this.tinyId=new TextDecoder().decode(n.data):n.tag===2&&(this.data=n.data)})}},Bl=new Set;function Ki(){let r=Math.floor(Math.random()*4294967296);return Bl.has(r)?Ki():(Bl.add(r),r)}var Gl=ve(Ve());var Xi=class extends Gl.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_currentState","DISCONNECTED");u(this,"_prevTime",-1);u(this,"_enableSEI");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}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)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(T.emit(f.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 hd=class extends Xi{constructor(e){super(M(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(this,"_flag",0);u(this,"_checkPublishStateTimeoutId",-1);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:n,smallVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:n||0,smallRtx:o||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,n=Object.keys(t).find(o=>t[o]!==s[o]);if(n)if(e)this._log.warn(`publish state not matched, ${n} local:${t[n]} server:${s[n]} ${cs()}`),P.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Z.run(di,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Z.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(It()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.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}get serverPublishState(){return{audio:!!(this.flag&ai),bigVideo:!!(this.flag&oi),smallVideo:!!(this.flag&Jr),auxVideo:!!(this.flag&Ni)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack)}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 o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,m,_,g,R,y;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:o,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,o.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new C({code:S.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264ENCODE})});Ce&&Ut()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ke["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(o.auxVideo=!0,a.auxVideo=t.muted):(o.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,o.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:X.SPC_PUBLISH,responseCommand:U.SPC_PUBLISH_RESULT,data:M(N({},this.singlePC.uplinkSSRC),{state:o,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),(d=this.singlePC.seiCodec)==null||d.handleEncodedStreams(),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s)t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e);else{if(t){this.localMainVideoTrack=t;let{scaleResolutionDownBy:L}=t;L>1&&(this._log.warn(`setScaleResolutionDownBy main ${L}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[1],L))}e&&(this.localMainAudioTrack=e)}yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((m=this.localAuxAudioTrack)==null?void 0:m.profile.bitrate),bigVideo:(_=this.localMainVideoTrack)==null?void 0:_.profile.bitrate,smallVideo:(R=(g=this.localMainVideoTrack)==null?void 0:g.small)==null?void 0:R.bitrate,auxVideo:(y=this.localAuxVideoTrack)==null?void 0:y.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){if(!Qe())return;this._log.info("publish by transceiver");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),d=[],l=[];if(a){let _=c[0].sender.replaceTrack(a);l.push(0),d.push(_)}if(o)if(n){let _=c[3].sender.replaceTrack(o);l.push(3),d.push(_)}else{let _=c[1].sender.replaceTrack(o);l.push(1),d.push(_)}if(s){let _=c[2].sender.replaceTrack(s);l.push(2),d.push(_)}let m=this.setTransceiverDirection(J.SENDONLY,l);return d.push(m),Promise.all(d)}enableSmall(e){return p(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(J.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(J.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}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 n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(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(J.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.sendWaitForResponseWithRetry({command:X.PUBLISH_STATE_CHANGE,data:t,responseCommand:U.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,commandDesc:"unpublish",responseCommand:U.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),At){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:X.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:U.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){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`),It()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===J.INACTIVE&&(yield this.setTransceiverDirection(J.SENDONLY,[o]))}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`),It()&&(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)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(J.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!Y)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
81
|
+
`).map(d=>{if(d.match(new RegExp(`a=(${J.INACTIVE}|${J.RECVONLY}|${J.SENDONLY})`))&&a++,t.includes(a)){if(e===J.INACTIVE&&d.includes(`a=${J.RECVONLY}`))return n=!0,`a=${e}`;if(e===J.SENDONLY&&d.includes(`a=${J.INACTIVE}`))return n=!0,`a=${J.RECVONLY}`}return d}).join(`\r
|
|
82
|
+
`);n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return p(this,null,function*(){var o;let t=(o=this._peerConnection)==null?void 0:o.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${s.kind} track on ${n?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!n&&t[1]&&(yield t[1].replaceTrack(s)),n&&t[3]&&(yield t[3].replaceTrack(s)))})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let o={};t===h.AUDIO?o.audio=e:s==="big"?o.bigVideo=e:s==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:X.UPDATE_MUTE_STAT,responseCommand:U.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(f.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===bi?(this._log.error(Ee.NOT_SUPPORTED_H264ENCODE),new C({code:S.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264ENCODE})})):new C({code:S.UNKNOWN,message:D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:U.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},md=hd;function Wl(r){return Object.keys(r).filter(i=>r[i])}var Ys=class extends Xi{constructor(e){super(M(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new qt(this._room,this),this.remoteVideoTrack=new bt(this._room,this),this.remoteAuxiliaryTrack=new Rr(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return _i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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 n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e;if(!t.id.includes(this.tinyId))return;let o=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${o} ${s.kind}`);let a=h.AUDIO;s.kind===h.VIDEO&&(a=o===h.MAIN?h.VIDEO:h.AUXILIARY);let c=this.remoteAudioTrack;a===h.VIDEO?c=this.remoteVideoTrack:a===h.AUXILIARY&&(c=this.remoteAuxiliaryTrack),c.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} ${Wl(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(n=>n===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new C({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,n;(e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting&&(this._log.warn("remote track ended start spc reconnect"),this.singlePC.startReconnection())}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 n=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${Wl(n)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,n),o==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=X.UNSUBSCRIBE,o=U.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=X.SUBSCRIBE_CHANGE,o=U.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:s,responseCommand:o,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:v.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._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}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:Ki(),bigVideoSsrc:Ki(),bigVideoRtxSsrc:Ki(),auxVideoSsrc:Ki(),auxVideoRtxSsrc:Ki()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:n,video:o,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:X.SPC_SUBSCRIBE,responseCommand:U.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},retries:3,retryTimeout:0});if(l.data.code!==0)throw new C({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}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.userId))})}};b([yt(),F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this.off("closed",s),t(new C({code:S.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Ys.prototype,"subscribe",1),b([yt()],Ys.prototype,"unsubscribe",1);var Jl=Ys;function jl(){return F(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;T.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Kl(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var{isString:Xl,isUndefined:wr,getNetworkType:n_,isEmpty:Zs}=De,Mt=class extends Uo{constructor(e){super(e);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=Is;this._changeBigSmallRecords=new Map;this._networkQuality=null;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 Ks(this,this._log),this.userManager=new po(this.userId,this._log),this._version=Te,this.sdpSemantics=zi,wr(e.sdpSemantics)?jt.isUnifiedPlanDefault()&&(this.sdpSemantics=ci):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${n_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=wr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!wr(e.enableSPC)&&Is&&(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",n=>{this.emit("peer-join",n)}),this.userManager.on("2",n=>{this.closeDownLinkConnection(n,"remote user exitRoom"),this.emit("peer-leave",n)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",o=>{var n=Ed(o,[]);T.emit(f.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},n)),this.emit("remote-publish-state-changed",N({},n))}),this._joinOptions=e,new Promise((n,o)=>p(this,null,function*(){var a,c;this._joinReject=o;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(d){if(d instanceof C&&d.code===S.SPC_INITIALIZED_FAILED)(a=this._signalChannel)==null||a.destroy(),yield this.initialize();else return o(d)}yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){o(d)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new si({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new C({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,n)=>p(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(le.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),n(m)}),ue((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Is&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={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:ga(),netType:mr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(o)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{n(new C({code:S.JOIN_ROOM_FAILED,message:D({key:v.JOIN_ROOM_TIMEOUT})}))},a),T.emit(f.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?X.SPC_JOIN_ROOM:X.JOIN_ROOM,o),this._signalChannel.once(U.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:_,message:g,data:R,tinyId:y}=m.data;T.emit(f.JOIN_RECEIVED_CMD_RES,{room:this,code:_}),_===0?(this._log.info("Join room success, start heartbeat"),y&&(this.tinyId=y),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${_} error: ${g}`),n(new C({code:S.JOIN_ROOM_FAILED,extraCode:_,message:D({key:v.JOIN_ROOM_FAILED,data:{error:g,code:_}})})))})}))}reJoin(e=!0){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(n=>(t=n,n)))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),s.push(this._signalChannel.connect())),yield Promise.all(s),yield this.doJoin(M(N({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey}),t),this._log.warn("reJoin success"),ee.logSuccessEvent({userId:this.userId,eventType:Me.REJOIN}),this.singlePC){let n=o=>{var a;o.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(kt.CONNECTION_STATE_CHANGED,n),this.uplinkConnection instanceof md&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(kt.CONNECTION_STATE_CHANGED,n),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Oo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),ee.logFailedEvent({userId:this.userId,eventType:Me.REJOIN,error:t}),this.emit("error",new C({code:S.JOIN_ROOM_FAILED,message:D({key:v.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this._signalChannel||fl(this.userId),n=!!(s&&s.isConnected&&s.keepAlive);return this._log.info(`${n?"reuse":"setup"} signal channel`),n?(s.url=e,s.backupUrl=t,s.room=this,this._signalChannel=s):this._signalChannel=new kr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._networkQuality||(this._networkQuality=new Ji({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(Ji.EVENT_NETWORK_QUALITY,o=>{this.emit("network-quality",o)})),Pe(this,this._signalChannel).add(le.CONNECTION_STATE_CHANGED,o=>{T.emit(f.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},o)),this.emit("signal-connection-state-changed",o)}).add(le.RECONNECT_FAILED,o=>{this.reset(),this.emit("error",o)}).add(U.PEER_JOIN,o=>{let{srcTinyId:a,userId:c,role:d}=o.data.data;this.userManager.addUser({userId:c,tinyId:a,role:d})}).add(U.PEER_LEAVE,o=>{let{userId:a,reason:c=0}=o.data.data;this.userManager.deleteUser(a,c)}).add(U.UPDATE_REMOTE_MUTE_STAT,o=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(o.data)}).add(U.CLIENT_BANNED,o=>{let a=o.data.data,{reason:c}=a;if(ee.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(le.SETUP_SUCCESS,o=>{this.tinyId=o.signalInfo.tinyId,T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(f.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this._signalChannel=e,e||pe(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(f.LEAVE_SEND_CMD,{room:this}),(e=this._signalChannel)==null||e.send(X.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(ht,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?$u(this.userId):[],n=N({str_sdk_version:Fr,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:mr()},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t);T.emit(f.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(X.ON_QUALITY_REPORT,n),this.emit("heartbeat-report",M(N({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:n,flag:o})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=o);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:n,flag:o}});T.emit(f.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 n=new(this.singlePC?Jl:Zc)({userId:e,tinyId:t,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}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("error",s=>{let n=s.getCode();n!==S.ICE_TRANSPORT_ERROR&&(n===S.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(ht,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:X.GET_USER_LIST,responseCommand:U.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:n}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:U.USER_LIST_RES,code:s,message:n}})}):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||!Xc)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(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof We&&!s.getIsReconnecting()){let n=s.getPeerConnection();n&&n.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ee.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Oo({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})),t.close()}this.remotePublishedUserMap.forEach(t=>{let s=new Zc({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:S.INVALID_OPERATION,message:D({key:v.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:X.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:U.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this._signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:n,message:o}=s.data;if(n!==0)throw new C({code:S.SWITCH_ROLE_FAILED,message:D({key:v.SWITCH_ROLE_FAILED,data:{message:o,code:n}})});this.role=e}).catch(s=>{throw s instanceof C&&s.getCode()===S.API_CALL_TIMEOUT&&(s=new C({code:S.SWITCH_ROLE_FAILED,message:D({key:v.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return p(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof ye&&(c instanceof Nt?s.audio=c:t.audio=c),c instanceof ae&&(c instanceof Ge&&c.mediaType===2?s.video=c:t.video=c)});let n=Zs(t),o=Zs(s);(!n||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new md({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Oo({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 d=c.getCode();d!==S.ICE_TRANSPORT_ERROR&&(d===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");n||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),o||(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(n=>{!n.mediaTrack||!n.isPublished||(n instanceof ye&&(n instanceof Nt?s.audio=n:t.audio=n),n instanceof ae&&(n instanceof Ge&&n.mediaType===2?s.video=n:t.video=n))});try{let n=e.map(o=>o.kind).join(",");Zs(t)||(this._log.info(`unpublish() => main ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Zs(s)||(this._log.info(`unpublish() => aux ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(n){}this.localTracks.size===0&&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||!Pa()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{T.emit(f.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(o=>!o.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=N({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 8:o.smallVideo=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),T.emit(f.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:s,subscribeState:o}),this._log.info(`subscribe() => ${t} ${n} [${vo(o)}] prev: [${vo(s.subscribeState)}]`),yield s.subscribe(o,n),this._log.info(`subscribe ${t} ${n} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(f.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})}catch(o){let a=o instanceof C?o.getCode():S.UNKNOWN,c=o;throw o instanceof C?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new C({code:S.API_CALL_ABORTED,message:D({key:v.API_CALL_ABORTED,data:{message:o.message,userId:t,streamType:n}})}),this._log.warn(c)):(c=new C({code:a,message:D({key:v.SUBSCRIBE_FAILED,data:{message:o.message,userId:t,streamType:n}})}),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 n=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${n}`);try{yield s.unsubscribe({remoteTracks:e,streamType:n})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),T.emit(f.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,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)),T.emit(f.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run(Qr,()=>{var n;let s=[];(n=this.remotePublishedUserMap)==null||n.forEach(o=>{if(o.muteState.hasAudio){let a=Math.floor(o.remoteAudioTrack.getAudioLevel()*100);s.push({userId:o.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:n,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,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,n]of this.remotePublishedUserMap)e==="main"&&n.muteState.hasVideo&&(t[s]=n.remoteVideoTrack.stat),e==="auxiliary"&&n.muteState.hasAuxiliary&&(t[s]=n.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(n=>s.push(De.getTurnServer(n))):De.isPlainObject(e)&&s.push(De.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:X.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:U.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:X.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:U.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?X.START_PUBLISH_TENCENT_CDN:X.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?U.START_PUBLISH_TENCENT_CDN_RES:U.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?X.STOP_PUBLISH_TENCENT_CDN:X.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?U.STOP_PUBLISH_TENCENT_CDN_RES:U.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this._signalChannel)==null||t.sendWaitForResponse({command:X.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:U.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=De.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{subscribeState:t,userId:s,muteState:{hasSmall:n,hasVideo:o}}=e;if(!n&&!o||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&n)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!n&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${qi-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=qi}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${qi-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let n={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:qi};this._changeBigSmallRecords.set(t.userId,n),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(Xl(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!wr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new C({code:S.INVALID_PARAMETER,message:D({key:v.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(!wr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new C({code:S.INVALID_PARAMETER,message:D({key:v.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!wr(e.userDefinePushArgs))if(Xl(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:S.INVALID_PARAMETER,message:D({key:v.INVALID_USER_DEFINE_PUSH_ARGS})});Zs(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}};b([Jc(["left",te.INIT],"joined"),Ri({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Tt(!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))}}),dl()],Mt.prototype,"join",1),b([Jc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),ul(),io("leave room"),Gs({fnName:"publish",validateArgs:!1}),Gs({fnName:"unsubscribe",validateArgs:!1})],Mt.prototype,"leave",1),b([yt(),jl(),Ri({settings:{retries:wt,timeout:r=>St(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),T.emit(f.PUBLISH_FAILED,{room:this}))}})],Mt.prototype,"publish",1),b([Gs({fnName:"publish"}),Mu("api-call"),yt(),Kl()],Mt.prototype,"unpublish",1),b([Ar((...r)=>r[0].userId),so(),ll(),Ri({settings:{retries:wt,timeout:r=>St(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),T.emit(f.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Mt.prototype,"subscribe",1),b([Gs({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")})}}),Ar((...r)=>r[0].userId)],Mt.prototype,"unsubscribe",1);Bs.create=Bs._create.bind(Bs,Mt);var jL=Bs;export{jL as default};
|