trtc-sdk-v5 5.10.2-beta.5 → 5.10.2-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/debug-dialog.js +2 -2
- package/index.d.ts +6 -23
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +32 -32
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var Yp=Object.create;var Bs=Object.defineProperty,Kp=Object.defineProperties,vu=Object.getOwnPropertyDescriptor,Zp=Object.getOwnPropertyDescriptors,ef=Object.getOwnPropertyNames,an=Object.getOwnPropertySymbols,Du=Object.getPrototypeOf,Ac=Object.prototype.hasOwnProperty,Ou=Object.prototype.propertyIsEnumerable,tf=Reflect.get;var Fs=Math.pow,Ic=(s,i,e)=>i in s?Bs(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,v=(s,i)=>{for(var e in i||(i={}))Ac.call(i,e)&&Ic(s,e,i[e]);if(an)for(var e of an(i))Ou.call(i,e)&&Ic(s,e,i[e]);return s},w=(s,i)=>Kp(s,Zp(i));var Mu=(s,i)=>{var e={};for(var t in s)Ac.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&an)for(var t of an(s))i.indexOf(t)<0&&Ou.call(s,t)&&(e[t]=s[t]);return e};var pi=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),fi=(s,i)=>{for(var e in i)Bs(s,e,{get:i[e],enumerable:!0})},rf=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of ef(i))!Ac.call(s,r)&&r!==e&&Bs(s,r,{get:()=>i[r],enumerable:!(t=vu(i,r))||t.enumerable});return s};var Be=(s,i,e)=>(e=s!=null?Yp(Du(s)):{},rf(i||!s||!s.__esModule?Bs(e,"default",{value:s,enumerable:!0}):e,s));var b=(s,i,e,t)=>{for(var r=t>1?void 0:t?vu(i,e):i,o=s.length-1,n;o>=0;o--)(n=s[o])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Bs(i,e,r),r};var d=(s,i,e)=>Ic(s,typeof i!="symbol"?i+"":i,e);var Fe=(s,i,e)=>tf(Du(s),e,i);var p=(s,i,e)=>new Promise((t,r)=>{var o=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(s,i)).next())});var Qe=pi((nE,Rc)=>{"use strict";var sf=Object.prototype.hasOwnProperty,ze="~";function $s(){}Object.create&&($s.prototype=Object.create(null),new $s().__proto__||(ze=!1));function of(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function ku(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new of(e,t||s,r),n=ze?ze+i:i;return s._events[n]?s._events[n].fn?s._events[n]=[s._events[n],o]:s._events[n].push(o):(s._events[n]=o,s._eventsCount++),s}function cn(s,i){--s._eventsCount===0?s._events=new $s:delete s._events[i]}function $e(){this._events=new $s,this._eventsCount=0}$e.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)sf.call(e,t)&&i.push(ze?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};$e.prototype.listeners=function(i){var e=ze?ze+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};$e.prototype.listenerCount=function(i){var e=ze?ze+i:i,t=this._events[e];return t?t.fn?1:t.length:0};$e.prototype.emit=function(i,e,t,r,o,n){var a=ze?ze+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,h,u;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){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,r),!0;case 5:return c.fn.call(c.context,e,t,r,o),!0;case 6:return c.fn.call(c.context,e,t,r,o,n),!0}for(u=1,h=new Array(l-1);u<l;u++)h[u-1]=arguments[u];c.fn.apply(c.context,h)}else{var f=c.length,g;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(i,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,e);break;case 3:c[u].fn.call(c[u].context,e,t);break;case 4:c[u].fn.call(c[u].context,e,t,r);break;default:if(!h)for(g=1,h=new Array(l-1);g<l;g++)h[g-1]=arguments[g];c[u].fn.apply(c[u].context,h)}}return!0};$e.prototype.on=function(i,e,t){return ku(this,i,e,t,!1)};$e.prototype.once=function(i,e,t){return ku(this,i,e,t,!0)};$e.prototype.removeListener=function(i,e,t,r){var o=ze?ze+i:i;if(!this._events[o])return this;if(!e)return cn(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&cn(this,o);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:cn(this,o)}return this};$e.prototype.removeAllListeners=function(i){var e;return i?(e=ze?ze+i:i,this._events[e]&&cn(this,e)):(this._events=new $s,this._eventsCount=0),this};$e.prototype.off=$e.prototype.removeListener;$e.prototype.addListener=$e.prototype.on;$e.prefixed=ze;$e.EventEmitter=$e;typeof Rc!="undefined"&&(Rc.exports=$e)});var Kn=pi((dS,Th)=>{"use strict";var gh=Th.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(gh).forEach(function(s){var i=gh[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ih=pi(vi=>{"use strict";var ms=function(s){return String(Number(s))===s?Number(s):s},i_=function(s,i,e,t){if(t&&!e)i[t]=ms(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=ms(s[r+1]))},r_=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;i_(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},Eh=Kn(),s_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);vi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(s_).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Eh[o]||[]).length;a+=1){var c=Eh[o][a];if(c.reg.test(n))return r_(c,t,n)}}),i.media=e,i};var Sh=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=ms(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};vi.parseParams=function(s){return s.split(/;\s?/).reduce(Sh,{})};vi.parseFmtpConfig=vi.parseParams;vi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};vi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(ms),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};vi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Sh,{})})};vi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=ms(e):(t=ms(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Rh=pi((uS,Ah)=>{"use strict";var Ad=Kn(),o_=/%[sdv%]/g,n_=function(s){var i=1,e=arguments,t=e.length;return s.replace(o_,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Io=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return n_.apply(null,r)},a_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c_=["i","c","b","a"];Ah.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||a_,t=i.innerOrder||c_,r=[];return e.forEach(function(o){Ad[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Io(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Io(o,n,a))})})}),s.media.forEach(function(o){r.push(Io("m",Ad.m[0],o)),t.forEach(function(n){Ad[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Io(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(Io(n,a,c))})})})}),r.join(`\r
|
|
1
|
+
var Wp=Object.create;var Us=Object.defineProperty,Jp=Object.defineProperties,yu=Object.getOwnPropertyDescriptor,jp=Object.getOwnPropertyDescriptors,qp=Object.getOwnPropertyNames,nn=Object.getOwnPropertySymbols,bu=Object.getPrototypeOf,Ec=Object.prototype.hasOwnProperty,Nu=Object.prototype.propertyIsEnumerable,Xp=Reflect.get;var Vs=Math.pow,Tc=(s,i,e)=>i in s?Us(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,v=(s,i)=>{for(var e in i||(i={}))Ec.call(i,e)&&Tc(s,e,i[e]);if(nn)for(var e of nn(i))Nu.call(i,e)&&Tc(s,e,i[e]);return s},M=(s,i)=>Jp(s,jp(i));var vu=(s,i)=>{var e={};for(var t in s)Ec.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&nn)for(var t of nn(s))i.indexOf(t)<0&&Nu.call(s,t)&&(e[t]=s[t]);return e};var li=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),ui=(s,i)=>{for(var e in i)Us(s,e,{get:i[e],enumerable:!0})},zp=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of qp(i))!Ec.call(s,r)&&r!==e&&Us(s,r,{get:()=>i[r],enumerable:!(t=yu(i,r))||t.enumerable});return s};var Ue=(s,i,e)=>(e=s!=null?Wp(bu(s)):{},zp(i||!s||!s.__esModule?Us(e,"default",{value:s,enumerable:!0}):e,s));var y=(s,i,e,t)=>{for(var r=t>1?void 0:t?yu(i,e):i,o=s.length-1,n;o>=0;o--)(n=s[o])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Us(i,e,r),r};var c=(s,i,e)=>Tc(s,typeof i!="symbol"?i+"":i,e);var Ve=(s,i,e)=>Xp(bu(s),e,i);var f=(s,i,e)=>new Promise((t,r)=>{var o=d=>{try{a(e.next(d))}catch(l){r(l)}},n=d=>{try{a(e.throw(d))}catch(l){r(l)}},a=d=>d.done?t(d.value):Promise.resolve(d.value).then(o,n);a((e=e.apply(s,i)).next())});var qe=li((KT,Sc)=>{"use strict";var Qp=Object.prototype.hasOwnProperty,je="~";function Bs(){}Object.create&&(Bs.prototype=Object.create(null),new Bs().__proto__||(je=!1));function Yp(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function Du(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new Yp(e,t||s,r),n=je?je+i:i;return s._events[n]?s._events[n].fn?s._events[n]=[s._events[n],o]:s._events[n].push(o):(s._events[n]=o,s._eventsCount++),s}function an(s,i){--s._eventsCount===0?s._events=new Bs:delete s._events[i]}function Be(){this._events=new Bs,this._eventsCount=0}Be.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Qp.call(e,t)&&i.push(je?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Be.prototype.listeners=function(i){var e=je?je+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};Be.prototype.listenerCount=function(i){var e=je?je+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Be.prototype.emit=function(i,e,t,r,o,n){var a=je?je+i:i;if(!this._events[a])return!1;var d=this._events[a],l=arguments.length,u,h;if(d.fn){switch(d.once&&this.removeListener(i,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,t),!0;case 4:return d.fn.call(d.context,e,t,r),!0;case 5:return d.fn.call(d.context,e,t,r,o),!0;case 6:return d.fn.call(d.context,e,t,r,o,n),!0}for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];d.fn.apply(d.context,u)}else{var m=d.length,_;for(h=0;h<m;h++)switch(d[h].once&&this.removeListener(i,d[h].fn,void 0,!0),l){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,t);break;case 4:d[h].fn.call(d[h].context,e,t,r);break;default:if(!u)for(_=1,u=new Array(l-1);_<l;_++)u[_-1]=arguments[_];d[h].fn.apply(d[h].context,u)}}return!0};Be.prototype.on=function(i,e,t){return Du(this,i,e,t,!1)};Be.prototype.once=function(i,e,t){return Du(this,i,e,t,!0)};Be.prototype.removeListener=function(i,e,t,r){var o=je?je+i:i;if(!this._events[o])return this;if(!e)return an(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&an(this,o);else{for(var a=0,d=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&d.push(n[a]);d.length?this._events[o]=d.length===1?d[0]:d:an(this,o)}return this};Be.prototype.removeAllListeners=function(i){var e;return i?(e=je?je+i:i,this._events[e]&&an(this,e)):(this._events=new Bs,this._eventsCount=0),this};Be.prototype.off=Be.prototype.removeListener;Be.prototype.addListener=Be.prototype.on;Be.prefixed=je;Be.EventEmitter=Be;typeof Sc!="undefined"&&(Sc.exports=Be)});var Yn=li((tS,fh)=>{"use strict";var ph=fh.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(ph).forEach(function(s){var i=ph[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Th=li(yi=>{"use strict";var us=function(s){return String(Number(s))===s?Number(s):s},zf=function(s,i,e,t){if(t&&!e)i[t]=us(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=us(s[r+1]))},Qf=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;zf(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},_h=Yn(),Yf=RegExp.prototype.test.bind(/^([a-z])=(.*)/);yi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(Yf).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(_h[o]||[]).length;a+=1){var d=_h[o][a];if(d.reg.test(n))return Qf(d,t,n)}}),i.media=e,i};var gh=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=us(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};yi.parseParams=function(s){return s.split(/;\s?/).reduce(gh,{})};yi.parseFmtpConfig=yi.parseParams;yi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};yi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(us),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};yi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(gh,{})})};yi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=us(e):(t=us(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Sh=li((rS,Eh)=>{"use strict";var Ed=Yn(),Kf=/%[sdv%]/g,Zf=function(s){var i=1,e=arguments,t=e.length;return s.replace(Kf,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Eo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return Zf.apply(null,r)},e_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],t_=["i","c","b","a"];Eh.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||e_,t=i.innerOrder||t_,r=[];return e.forEach(function(o){Ed[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Eo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Eo(o,n,a))})})}),s.media.forEach(function(o){r.push(Eo("m",Ed.m[0],o)),t.forEach(function(n){Ed[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Eo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){r.push(Eo(n,a,d))})})})}),r.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var Ch=pi(Kt=>{"use strict";var Ir=Ih(),d_=Rh(),l_=Kn();Kt.grammar=l_;Kt.write=d_;Kt.parse=Ir.parse;Kt.parseParams=Ir.parseParams;Kt.parseFmtpConfig=Ir.parseFmtpConfig;Kt.parsePayloads=Ir.parsePayloads;Kt.parseRemoteCandidates=Ir.parseRemoteCandidates;Kt.parseImageAttributes=Ir.parseImageAttributes;Kt.parseSimulcastStreamList=Ir.parseSimulcastStreamList});var uu=pi((Bw,sp)=>{"use strict";var rp=sp.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(rp).forEach(function(s){var i=rp[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var ap=pi($i=>{"use strict";var Ls=function(s){return String(Number(s))===s?Number(s):s},MT=function(s,i,e,t){if(t&&!e)i[t]=Ls(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Ls(s[r+1]))},kT=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;MT(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},op=uu(),LT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);$i.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(LT).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(op[o]||[]).length;a+=1){var c=op[o][a];if(c.reg.test(n))return kT(c,t,n)}}),i.media=e,i};var np=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Ls(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};$i.parseParams=function(s){return s.split(/;\s?/).reduce(np,{})};$i.parseFmtpConfig=$i.parseParams;$i.parsePayloads=function(s){return s.toString().split(" ").map(Number)};$i.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Ls),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};$i.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(np,{})})};$i.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Ls(e):(t=Ls(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var dp=pi(($w,cp)=>{"use strict";var hu=uu(),PT=/%[sdv%]/g,wT=function(s){var i=1,e=arguments,t=e.length;return s.replace(PT,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Zo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return wT.apply(null,r)},xT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],UT=["i","c","b","a"];cp.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||xT,t=i.innerOrder||UT,r=[];return e.forEach(function(o){hu[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Zo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Zo(o,n,a))})})}),s.media.forEach(function(o){r.push(Zo("m",hu.m[0],o)),t.forEach(function(n){hu[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Zo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(Zo(n,a,c))})})})}),r.join(`\r
|
|
3
|
+
`}});var Ih=li(Xt=>{"use strict";var Er=Th(),i_=Sh(),r_=Yn();Xt.grammar=r_;Xt.write=i_;Xt.parse=Er.parse;Xt.parseParams=Er.parseParams;Xt.parseFmtpConfig=Er.parseFmtpConfig;Xt.parsePayloads=Er.parsePayloads;Xt.parseRemoteCandidates=Er.parseRemoteCandidates;Xt.parseImageAttributes=Er.parseImageAttributes;Xt.parseSimulcastStreamList=Er.parseSimulcastStreamList});var cu=li((mw,Zm)=>{"use strict";var Km=Zm.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(Km).forEach(function(s){var i=Km[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var ip=li(Vi=>{"use strict";var ks=function(s){return String(Number(s))===s?Number(s):s},CT=function(s,i,e,t){if(t&&!e)i[t]=ks(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=ks(s[r+1]))},RT=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;CT(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},ep=cu(),yT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Vi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(yT).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(ep[o]||[]).length;a+=1){var d=ep[o][a];if(d.reg.test(n))return RT(d,t,n)}}),i.media=e,i};var tp=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=ks(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Vi.parseParams=function(s){return s.split(/;\s?/).reduce(tp,{})};Vi.parseFmtpConfig=Vi.parseParams;Vi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Vi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(ks),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Vi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(tp,{})})};Vi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=ks(e):(t=ks(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var sp=li((fw,rp)=>{"use strict";var du=cu(),bT=/%[sdv%]/g,NT=function(s){var i=1,e=arguments,t=e.length;return s.replace(bT,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Yo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return NT.apply(null,r)},vT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],DT=["i","c","b","a"];rp.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||vT,t=i.innerOrder||DT,r=[];return e.forEach(function(o){du[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Yo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Yo(o,n,a))})})}),s.media.forEach(function(o){r.push(Yo("m",du.m[0],o)),t.forEach(function(n){du[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Yo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){r.push(Yo(n,a,d))})})})}),r.join(`\r
|
|
4
4
|
`)+`\r
|
|
5
|
-
`}});var mu=pi(Hi=>{"use strict";var Vr=ap(),VT=dp();Hi.write=VT;Hi.parse=Vr.parse;Hi.parseParams=Vr.parseParams;Hi.parseFmtpConfig=Vr.parseFmtpConfig;Hi.parsePayloads=Vr.parsePayloads;Hi.parseRemoteCandidates=Vr.parseRemoteCandidates;Hi.parseImageAttributes=Vr.parseImageAttributes;Hi.parseSimulcastStreamList=Vr.parseSimulcastStreamList});import D1 from"webrtc-adapter";var zm=Be(Qe());var Lu=(V=>(V[V.INVALID_PARAMETER=4096]="INVALID_PARAMETER",V[V.INVALID_OPERATION=4097]="INVALID_OPERATION",V[V.NOT_SUPPORTED=4098]="NOT_SUPPORTED",V[V.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",V[V.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",V[V.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",V[V.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",V[V.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",V[V.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",V[V.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",V[V.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",V[V.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",V[V.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",V[V.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",V[V.CLIENT_BANNED=16448]="CLIENT_BANNED",V[V.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",V[V.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",V[V.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",V[V.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",V[V.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",V[V.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",V[V.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",V[V.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",V[V.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",V[V.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",V[V.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",V[V.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",V[V.API_CALL_ABORTED=16461]="API_CALL_ABORTED",V[V.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",V[V.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",V[V.UNKNOWN=65535]="UNKNOWN",V))(Lu||{}),S=Lu;var nf=function(s){for(let i in S)if(S[i]===s)return i;return"UNKNOWN"},Cc=class extends Error{constructor({name:e="RtcError",message:t,code:r=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${nf(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},y=Cc;var Pu=new Date().getTime(),yc=0,wu=function(s){Pu=s,yc=Pu-new Date().getTime();let i=new Date;i.setTime(s),R.info(`baseTime from server: ${i} offset: ${yc}`)},Hs=function(){return new Date().getTime()+yc},dn=function(){let s=new Date;return s.setTime(Hs()),s.toLocaleString()},ln=function(s){let i=String(s.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${s.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var dt={};fi(dt,{bytes2ms:()=>Gu,convertObjectNumberToInt:()=>to,copyProperties:()=>Hu,deepClone:()=>hr,deepMerge:()=>Wt,delay:()=>Ii,fibonacci:()=>pr,formatedTime:()=>Yu,getConstructorName:()=>Xr,getContainerFromElement:()=>Qu,getEnv:()=>Fu,getInternalVersion:()=>Xu,getLoggerUrl:()=>Ei,getMediaStreamTrackInfo:()=>Nn,getMuteStateFromFlag:()=>Si,getNetworkType:()=>Bc,getNumNetworkType:()=>mr,getReconnectionTimeout:()=>vt,getStringByteLength:()=>eo,getTurnServer:()=>zu,getUint32Version:()=>Cn,getValueType:()=>Ee,getViewListFromView:()=>Yr,glog:()=>Hc,ipv4ToUint32:()=>Qr,isArray:()=>_e,isAudioWorkletSupported:()=>qu,isBoolean:()=>ge,isConstructor:()=>fr,isEmpty:()=>zr,isFunction:()=>se,isLangChinese:()=>Nt,isMediaStreamTrack:()=>Ju,isNumber:()=>Q,isObject:()=>bt,isOverseaSdkAppId:()=>Zs,isPlainObject:()=>He,isPortrait:()=>Rn,isPromise:()=>qi,isRemoteTrack:()=>ju,isString:()=>K,isUndefined:()=>E,loadImage:()=>Kr,ms2bytes:()=>Wu,ms2samples:()=>$c,normalizeUrl:()=>bn,performanceNow:()=>x,promiseAny:()=>_r,samples2ms:()=>Fc,setNetworkType:()=>In,stringify:()=>Tt,stringifyIncludeValue:()=>An,throttlePromise:()=>yn});var Vc={};fi(Vc,{AUDIO_MUTE_BIT:()=>gn,AUDIO_STAT_BIT:()=>Ji,AUX_STAT_BIT:()=>dr,AUX_STREAM_MSID:()=>Mc,BACKEND_ENV:()=>_n,BASE_DOC_URL:()=>Ht,BASE_HOST:()=>xu,CAPABILITIES_KEYS:()=>Sn,CLASS_NAME:()=>vf,CLOUD_CONSOLE_URL:()=>lf,CROSS_ROOM_BIT:()=>Oc,DATA_FREEZE_TIMING:()=>En,DEFAULT_ASSETS_URL:()=>un,DOC_URL:()=>uf,DTLS_STATE_UNKNOWN:()=>yt,ENV_NAME:()=>_i,EXCHANGE_SDP_TIMEOUT:()=>xc,IS_WORKER:()=>Wr,IS_WORKLET:()=>Ws,KIBANA_EVENT:()=>rt,LOCAL_STREAM_PUBLISH_STATE:()=>Vu,LOGGER_CMD_TYPE:()=>Gi,LOGGER_DOMAIN:()=>Nc,LOGGER_DOMAIN_OVERSEA:()=>vc,LOG_LEVEL:()=>Ct,LOG_LEVEL_NAME:()=>Of,MAIN_STREAM_MSID:()=>qs,MAX_RTT:()=>Ys,MICROPHONE_COMMUNICATIONS:()=>Df,MICROPHONE_DEFAULT:()=>ur,MUTE_ALL_BIT:()=>pf,NAME:()=>m,NETWORK_TYPE:()=>hn,NOT_SUPPORTED_H264:()=>lr,PAUSED_RETRY_COUNT:()=>zs,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Xs,PEER_CONNECTION_STATE:()=>me,PEER_LEAVE_REASON:()=>Uc,RECOVER_CAPTURE_INTERVAL:()=>qr,REMOTE_STREAM_TYPE_AUX:()=>Lc,REMOTE_STREAM_TYPE_MAIN:()=>kc,RENDER_FREEZE_TIMING:()=>Cf,SCHEDULE_DOMAIN:()=>Ti,SCHEDULE_TIMEOUT:()=>Nf,SDP_SEMANTICS_PLAN_B:()=>Jr,SDP_SEMANTICS_UNIFIED_PLAN:()=>ji,SECOND_HOST:()=>cf,SIGNAL_PING_PONG_INTERVAL:()=>mf,SIGNAL_PING_TIMEOUT:()=>hf,SIGNAL_RECONNECTION_COUNT:()=>Af,SMALL_STAT_BIT:()=>js,SPEAKER_DEFAULT:()=>Qs,STORAGE_EXPIRES_TIME:()=>mn,STREAM_TYPE_BIG:()=>yf,STREAM_TYPE_SMALL:()=>bf,SUBSCRIBE_SMALL_RETRY_COUNT:()=>jr,SYNC_USER_LIST_INTERVAL:()=>Rf,Scene:()=>Gt,THIRD_HOST:()=>df,TRANSPORT_DIRECTION:()=>Z,TRTC_ERROR_ASSISTANCE:()=>Dc,TRTC_QUALITY_BAD:()=>Ef,TRTC_QUALITY_DISCONNECTED:()=>If,TRTC_QUALITY_EXCELLENT:()=>_f,TRTC_QUALITY_GOOD:()=>gf,TRTC_QUALITY_POOR:()=>Tf,TRTC_QUALITY_UNKNOWN:()=>ff,TRTC_QUALITY_VERY_BAD:()=>Sf,UPDATE_OFFER_TIMEOUT:()=>wc,VIDEO_MUTE_BIT:()=>Tn,VIDEO_STAT_BIT:()=>Wi,audioProfileMap:()=>pn,getRetryCount:()=>gi,getScriptDir:()=>af,innerVersion:()=>Gs,loggerProxy:()=>Js,screenProfileMap:()=>fn,setLoggerProxy:()=>cr,setRetryCount:()=>Pc,setVersion:()=>bc,version:()=>Me,videoProfileMap:()=>gt});var Gs="4.15.00.1600",Me="5.0.0";function bc(s){Me=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));Gs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Wr=typeof importScripts!="undefined",Ws=typeof registerProcessor!="undefined",af=()=>{let s=Wr?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},Js="",cr=s=>Js=s,xu="web.sdk.qcloud.com",cf="web.sdk.tencent.cn",df="web.sdk.cloud.tencent.cn",lf="https://console.cloud.tencent.com/trtc",Ht=`https://${xu}/trtc/webrtc/v5/doc`,un="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",uf=`${Ht}/zh-cn/`,Nc="https://yun.tim.qq.com",vc="https://apisgp.my-imcloud.com",Dc="trtc_error_assistance",Gi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},_i={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Ct=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(Ct||{}),hf=18e3,mf=2e3,hn={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},mn=7*24*3600*1e3,pn={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}},gt={"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}},fn={"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}},m={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",LOADEDMETADATA:"loadedmetadata",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"},Z={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},_n={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Gt=(e=>(e.LIVE="live",e.RTC="rtc",e))(Gt||{}),Wi=1,js=2,dr=4,Ji=8,gn=64,Tn=16,pf=112,Oc=128,qs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Mc="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",kc=m.MAIN,Lc=m.AUXILIARY,ff=0,_f=1,gf=2,Tf=3,Ef=4,Sf=5,If=6,yt="unknown",me={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Uu=1/0;function Pc(s){Uu=s}function gi(){return Uu}var Af=30,rt={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"},Rf=1e4,wc=1e4,xc=1e4,ji="unified-plan",Jr="plan-b",lr=1028,Vu=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Vu||{}),En=500,Cf=1e3,yf=m.BIG,bf=m.SMALL,Xs=10*1e3,Ti={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Nf=2e3,vf={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},zs=5,ur="default",Qs=ur,Df="communications",Of=Object.keys(Ct),Uc=["normal leave","timeout leave","kick","role change"],jr=10,qr=2e3,Sn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Ys=10*1e3;var Fu=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Zs=s=>Number(s)<14e8,Ei=function(s,i){let e;Js?e=Js:e=Zs(s)?vc:Nc;let t=Math.floor(Math.random()*Fs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},Ks="unknown";function Bc(){if(Ks!=="unknown")return Ks;let{userAgent:s,connection:i}=navigator,e=(s.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t&&(Ks=$u(t,r)),Ks}function $u(s,i){if(hn[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function In(s){Ks=$u(s)}function mr(){return hn[Bc()]}function Hu(s,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(s,e,t)}return s}function Gu(s,i=48e3){return Fc(s/4,i)}function Fc(s,i=48e3){return s*1e3/i}function Wu(s,i=48e3){return $c(s,i)*4}function $c(s,i=48e3){return s*i/1e3}var Hc=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Nt=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},He=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 pr(s,i=1,e=1){return s<=1?e:pr(s-1,e,i+e)}function vt(s){return s>8?30*1e3:pr(s)*1e3}function Ee(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var se=s=>typeof s=="function",E=s=>typeof s=="undefined",K=s=>typeof s=="string",Q=s=>typeof s=="number",ge=s=>typeof s=="boolean",bt=s=>Ee(s)==="object",_e=s=>Ee(s)==="array",Ju=s=>Ee(s)==="MediaStreamTrack".toLowerCase(),ju=s=>s.isRemote,qi=s=>Ee(s)==="promise",fr=s=>se(s)&&s.prototype.constructor===s,Xr=s=>fr(s)?s.prototype.constructor.name:"",qu=typeof AudioWorkletNode!="undefined";function _r(s){return new Promise((i,e)=>{let t=[];s.forEach(r=>{r.then(i).catch(o=>{t.push(o),t.length===s.length&&e(t)})})})}function x(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Bu=s=>+s<10?`0${s}`:s,Xu=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=Bu(e[1])+Bu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Mf=Object.prototype.hasOwnProperty,{toString:_E}=Object.prototype;function zr(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(He(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(Mf.call(s,i))return!1;return!0}}return!1}function Si(s,i){return{userId:i,hasAudio:!!(s&Ji),hasVideo:!!(s&Wi),hasAuxiliary:!!(s&dr),hasSmall:!!(s&js),audioMuted:!!(s&gn),videoMuted:!!(s&Tn),audioAvailable:!!(s&Ji)&&!(s&gn),videoAvailable:!!(s&Wi)&&!(s&Tn)}}function zu(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!E(s.username)&&!E(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",E(s.credentialType)||(i.credentialType=s.credentialType)),i}function Qr(s,i=!0){if(!K(s))return 0;let e=s.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(s,i,e,t){if(!(bt(s)&&bt(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(E(i[n])||e&&e.includes(n)))if(bt(s[n])&&bt(i[n]))r+=Wt(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=hr(i[n]),r+=1)}return r};function hr(s){if(_e(s)){let i=[];return s.forEach((e,t)=>{i[t]=hr(e)}),i}if(bt(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=hr(s[e])}),i}return s}var Yr=s=>{let i=[];if(_e(s))i=[...s];else if(K(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},Qu=s=>K(s)?document.getElementById(s):s,kf=s=>{let i=c=>c<10?`0${c}`:`${c}`,e=s.getFullYear(),t=s.getMonth()+1,r=s.getDate(),o=i(s.getHours()),n=i(s.getMinutes()),a=i(s.getSeconds());return`${e}/${t}/${r} ${o}:${n}:${a}`},Yu=()=>kf(new Date);function Tt(s,{keysToInclude:i,keysToExclude:e}){try{if(_e(s))return`[${s.map(n=>Tt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!He(s)||!_e(i)&&!_e(e))return JSON.stringify(s);let t={},r=new Set(i),o=new Set(e);return Object.keys(s).forEach(n=>{(o.size===0&&r.has(n)||r.size===0&&!o.has(n))&&(t[n]=He(s[n])||_e(s[n])?JSON.parse(Tt(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function An(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),Tt(s,{keysToInclude:e})}function eo(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Rn=()=>{var s,i,e,t;return(s=window.screen)!=null&&s.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},Kr=s=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(K(s))t=new Image,t.crossOrigin="anonymous",t.src=s;else if(t=s,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new y({code:S.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),Cn=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},to=s=>(Object.keys(s).forEach(i=>{Q(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(He(s[i])||_e(s[i]))&&to(s[i])}),s);function Ii(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function yn(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function bn(s){return s.replace(/(^|[^:])\/{2,}/g,"$1/")}function Nn(s){var i;try{let{width:e,height:t,frameRate:r,sampleRate:o,sampleSize:n,channelCount:a}=(i=s.getSettings)==null?void 0:i.call(s),c=s.kind===m.AUDIO?`${o}x${n}@${a}`:`${e}x${t}@${r}`,l=s.stats?` stats: ${JSON.stringify(s.stats).replaceAll('"',"")}`:"";return`${s.id} ${s.readyState} muted:${s.muted} ${s.kind} ${s.label} ${c}${l}`}catch(e){return""}}function Ai({url:s,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((o,n)=>{if("fetch"in window)return fetch(s,{method:e,body:i,priority:r}).then(c=>c.text()).then(c=>{try{o({data:JSON.parse(c)})}catch(l){o({data:c})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);o({data:c})}catch(c){o({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,s,!0),a.send(i)})}function Gc(s){return p(this,null,function*(){let i=x(),e=JSON.stringify(s);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${x()-i}ms`),a}catch(t){return e}})}var Lf=Object.prototype.hasOwnProperty;var Jt=s=>typeof s=="function",Ri=s=>typeof s=="undefined";var vn=s=>typeof s=="boolean";var Wc=s=>s.isRemote;var Pf=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 Ku(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Pf(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(Lf.call(s,i))return!1;return!0}}return!1}var wf=0,xf=1,Zu=2;function Uf({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,h=0,u=-1,f=wf,g=(D,_)=>p(this,null,function*(){let C=n||this;try{let M=yield s.apply(C,a);h>0&&o&&o.call(this,h),h=0,D(M)}catch(M){let ne=()=>{clearTimeout(u),h=0,f=Zu,_(M)},F=()=>{f!==Zu&&h<(Jt(c)?c():c)?(h++,f=xf,Jt(t)&&t.call(this,h,ne),u=window.setTimeout(()=>{u=-1,g(D,_)},Jt(l)?l(h):l)):(ne(),Jt(r)&&r.call(this,M))};Jt(e)?e.call(this,{error:M,retry:F,reject:_,retryFuncArgs:a,retriedCount:h}):F()}});return new Promise(g)}}var jt=Uf;var Zr=class{constructor(i){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=vn(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}`:""}]`),R.log(i,e,Ri(this.userId)||Ku(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 ls={};fi(ls,{ANDROID_VERSION:()=>qc,CHROME_MAJOR_VERSION:()=>lt,CHROME_VERSION:()=>Jn,EDGE_VERSION:()=>On,EDG_MAJOR_VERSION:()=>Xc,EDG_VERSION:()=>Mn,FIREFOX_MAJOR_VERSION:()=>io,FIREFOX_VERSION:()=>Dn,HUAWEI_VERSION:()=>$n,IE_VERSION:()=>Hf,IOS_MAIN_VERSION:()=>ut,IOS_VERSION:()=>Xt,IPADQQB_VERSION:()=>Bn,IS_ANDROID:()=>he,IS_ANDROID_WEBVIEW:()=>jf,IS_ANY_SAFARI:()=>zi,IS_CHROME:()=>ds,IS_CHROME_OS:()=>zc,IS_CHROMIUM_BASE:()=>Ye,IS_DESKTOP_IOS_CHROME:()=>sd,IS_EDG:()=>rs,IS_EDGE:()=>is,IS_ELECTRON:()=>Wf,IS_FIREFOX:()=>oe,IS_HEADLESS_CHROME:()=>ed,IS_HONOR:()=>Kc,IS_HUAWEI:()=>Yc,IS_HUAWEIBROWSER:()=>uo,IS_IE:()=>rh,IS_IE8:()=>$f,IS_IOS:()=>Se,IS_IOS_13_OR_14:()=>rd,IS_IOS_15_1:()=>id,IS_IOS_CHROME:()=>sh,IS_IPAD:()=>ts,IS_IPADQQB:()=>ao,IS_IPAD_PRO:()=>jc,IS_IPHONE:()=>Xi,IS_IPOD:()=>ih,IS_LINUX:()=>co,IS_LOCAL:()=>Lt,IS_MAC:()=>kt,IS_MACQQB:()=>no,IS_MIBROWSER:()=>lo,IS_MQQB:()=>as,IS_NATIVE_ANDROID:()=>Ff,IS_OLD_ANDROID:()=>Bf,IS_OPENHARMONY:()=>Zc,IS_OPPOBROWSER:()=>mo,IS_SAFARI:()=>Le,IS_SAFARI_15_1:()=>qf,IS_SAMSUNGBROWSER:()=>ho,IS_SOGOU:()=>so,IS_SOGOUM:()=>ro,IS_TBS:()=>Mt,IS_UCBROWSER:()=>Qc,IS_VIVOBROWSER:()=>po,IS_WECHAT:()=>os,IS_WIN:()=>gr,IS_WQQB:()=>oo,IS_WX:()=>Gf,IS_X5MQQB:()=>ns,IS_XWEB:()=>ss,MACQQB_VERSION:()=>Vn,MI_VERSION:()=>Fn,MQQB_VERSION:()=>es,OPENHARMONY_VERSION:()=>Jf,OPPO_VERSION:()=>Gn,SAFARI_VERSION:()=>Ci,SAMSUNG_VERSION:()=>Hn,SOGOUM_VERSION:()=>kn,SOGOU_VERSION:()=>Ln,TBS_VERSION:()=>Pn,UA_DATA_STRING:()=>Dt,USER_AGENT:()=>Ot,VIVO_VERSION:()=>Wn,WECHAT_VERSION:()=>xn,WQQB_VERSION:()=>Un,XWEB_VERSION:()=>wn,browserInfo:()=>qt,getBrowserInfo:()=>oh,getChromeMajorVersion:()=>cs,getDeviceModel:()=>Tr,getGPUInfo:()=>nd,getOSName:()=>jn,getOSNumber:()=>_o,getOSString:()=>bi,getOSType:()=>Xf,getTerminalType:()=>ad,getUserAgentData:()=>fo,isLocalStorageEnabled:()=>yi,isMobile:()=>od,isVersionSmallerThan:()=>td});var Ot=typeof navigator=="undefined"?"":navigator.userAgent,X=s=>new RegExp(s,"i").test(Ot),Ne=s=>{if(X(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=Ot.match(i);if(e&&e[1])return e[1]}return""},Jc=s=>{if(X(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=Ot.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},eh=/AppleWebKit\/([\d.]+)/i.exec(Ot),Vf=eh?parseFloat(eh[1]):NaN,ts=X("iPad"),jc=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),Xi=X("iPhone")&&!ts,ih=X("iPod"),Se=Xi||ts||ih||jc,he=X("Android"),qc=function(){if(he){let s=Ot.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(s){let i=s[1]&&parseFloat(s[1]),e=s[2]&&parseFloat(s[2]);if(i&&e)return parseFloat(`${s[1]}.${s[2]}`);if(i)return i}}return NaN}(),Bf=he&&X("webkit")&&qc<2.3,Ff=he&&qc<5&&Vf<537,oe=X("Firefox"),Dn=Ne("Firefox"),io=Jc("Firefox"),is=X("Edge"),On=Ne("Edge"),rs=X("Edg"),Mn=Ne("Edg"),Xc=Jc("Edg"),ro=X("SogouMobileBrowser"),kn=Ne("SogouMobileBrowser"),so=X("MetaSr\\s"),Ln=Ne("MetaSr\\s"),Mt=X("TBS"),Pn=Ne("TBS"),ss=X("XWEB"),wn=Ne("XWEB"),$f=X("MSIE\\s8\\.0"),rh=X("MSIE\\/\\d+"),Hf=function(){if(rh){let s=/MSIE\s(\d+)\.\d/.exec(Ot),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(Ot)&&/rv:11.0/.test(Ot)&&(i=11),i}return NaN}(),os=X("(micromessenger|webbrowser)"),xn=Ne("MicroMessenger"),ns=!Mt&&X("MQQBrowser")&&X("COVC"),as=!Mt&&X("MQQBrowser")&&!X("COVC"),es=as||ns?Ne("MQQBrowser"):"",oo=!Mt&&X(" QQBrowser"),Un=Ne(" QQBrowser"),no=!Mt&&X("QQBrowserLite"),Vn=Ne("QQBrowserLite"),ao=!Mt&&X("MQBHD"),Bn=Ne("MQBHD"),gr=X("Windows"),kt=!Se&&X("MAC OS X"),co=!he&&X("Linux"),zc=X("CrOS"),Gf=X("MicroMessenger"),Qc=X("UCBrowser"),Wf=X("Electron"),lo=X("MiuiBrowser"),Fn=Ne("MiuiBrowser"),uo=X("HuaweiBrowser"),Yc=X("Huawei")||X("HUAWEI"),Kc=X("Honor")||X("HONOR"),$n=Ne("HuaweiBrowser"),ho=X("SamsungBrowser"),Hn=Ne("SamsungBrowser"),mo=X("HeyTapBrowser"),Gn=Ne("HeyTapBrowser"),po=X("VivoBrowser"),Wn=Ne("VivoBrowser"),Zc=X("OpenHarmony"),Jf=Ne("OpenHarmony"),cs=()=>Jc("Chrome"),Ye=X("Chrome"),ds=!is&&!so&&!ro&&!Mt&&!ss&&!rs&&!oo&&!lo&&!uo&&!ho&&!mo&&!po&&Ye,ed=X("HeadlessChrome"),lt=cs(),Jn=Ne("Chrome"),Le=!Ye&&!as&&!ns&&!no&&!ao&&X("Safari"),zi=Le||Se,Ci=Ne("Version"),jf=/Android.*(wv|.0.0.0)/.test(Ot),Xt=(()=>{if(jc)return Ci;if(Se){let s=Ot.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})();function td(s,i){let e=s.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let o=e[r]||0,n=t[r]||0;if(o<n)return!0;if(o>n)return!1}return!1}var ut=Number(Xt.split(".")[0]),qf=Ci==="15.1",id=Xt==="15.1",rd=(()=>{let s=Number(Xt.split(".")[0]);return s===14||s===13})(),sh=X("CriOS"),sd=sh&&Ci==="11.1.1",Lt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",yi=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),qt=oh();function oh(){let s=new Map([[oe,["Firefox",Dn]],[rs,["Edg",Mn]],[ds,["Chrome",Jn]],[Le,["Safari",Ci]],[Mt,["TBS",Pn]],[ss,["XWEB",wn]],[os&&Xi,["WeChat",xn]],[oo,["QQ(Win)",Un]],[as,["QQ(Mobile)",es]],[ns,["QQ(Mobile X5)",es]],[no,["QQ(Mac)",Vn]],[ao,["QQ(iPad)",Bn]],[lo,["MI",Fn]],[uo,["HW",$n]],[ho,["Samsung",Hn]],[mo,["OPPO",Gn]],[po,["VIVO",Wn]],[is,["EDGE",On]],[ro,["SogouMobile",kn]],[so,["Sogou",Ln]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var ae=null;function od(){return ae&&typeof ae.mobile=="boolean"?ae.mobile:he||Se||Xi||ts||Zc}var Dt="";function fo(){return p(this,null,function*(){if(ae)return ae;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return ae=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ae&&!Dt&&(Dt=`UAData: ${ae.platform}/${ae.platformVersion}`,ae.architecture&&ae.bitness&&(Dt+=` ${ae.architecture}/${ae.bitness}`),ae.mobile&&(Dt+=" mobile"),ae.model&&(Dt+=` model: ${ae.model.replace(/\s+/g,"/")}`),ae.fullVersionList&&(Dt+=` ${ae.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),ae}catch(s){return null}})}function nd(){try{let s=document.createElement("canvas"),i=s.getContext("webgl")||s.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(s){return""}}function Tr(){return(ae==null?void 0:ae.model)||""}var th=new Map([[he,"Android"],[Se,"iOS"],[gr,"Windows"],[kt,"MacOS"],[co,"Linux"],[zc,"ChromeOS"]]),jn=function(){return th.get(!0)?th.get(!0):ae?ae.platform:"unknown"};function _o(){return gr?1:he?2:kt?3:Se?4:co?5:zc?6:0}var bi=()=>{let s=jn();return s+=`/${qt.name}/${Le?qt.version:qt.version.split(".")[0]}`,ae!=null&&ae.platformVersion&&(s+=`/${ae.platformVersion}`),ae!=null&&ae.architecture&&(s+=`/${ae.architecture}`),s};function ad(){return he?4:Xi?2:ts?3:kt?12:gr?5:co?13:Zc?22:1}function Xf(){return he?"Android":Xi?"iPhone":ts?"iPad":kt?"Mac":gr?"Windows":co?"Linux":"unknown"}var nh=Be(Qe(),1),zf=new nh.default,T=zf;var zt=(J=>(J.ROOM_DESTROY="1",J.JOIN_START="21",J.JOIN_SCHEDULE_SUCCESS="22",J.JOIN_SIGNAL_CONNECTION_START="23",J.JOIN_SIGNAL_CONNECTION_END="24",J.JOIN_SEND_CMD="25",J.JOIN_RECEIVED_CMD_RES="26",J.JOIN_SUCCESS="27",J.JOIN_FAILED="28",J.LEAVE_START="51",J.LEAVE_SEND_CMD="52",J.LEAVE_SUCCESS="53",J.PUBLISH_START="61",J.SEND_FIRST_VIDEO_FRAME="62",J.PUBLISH_FAILED="63",J.SUBSCRIBE_START="81",J.SUBSCRIBE_SUCCESS="82",J.SUBSCRIBE_FAILED="84",J.UNSUBSCRIBE_SUCCESS="83",J.LOCAL_TRACK_CAPTURE_START="101",J.LOCAL_TRACK_CAPTURE_SUCCESS="102",J.LOCAL_TRACK_CAPTURE_FAILED="103",J.LOCAL_TRACK_PUBLISHED="104",J.LOCAL_TRACK_UNPUBLISHED="105",J.LOCAL_TRACK_REPLACED="106",J.SWITCH_DEVICE_SUCCESS="107",J.TRACK_MUTED="108",J.TRACK_UNMUTED="109",J.REMOTE_TRACK_SUBSCRIBED="110",J.REMOTE_TRACK_UNSUBSCRIBED="111",J.LOCAL_TRACK_RECAPTURE="112",J.LOCAL_AUDIO_STARTED="113",J.LOCAL_AUDIO_STOPPED="114",J.REMOTE_AUDIO_STARTED="115",J.REMOTE_AUDIO_STOPPED="116",J.PLAY_TRACK_START="151",J.PLAYER_STATE_CHANGED="152",J.VIDEO_LOADED_DATA="153",J.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",J.SIGNAL_CONNECTION_STATE_CHANGED="201",J.PEER_CONNECTION_STATE_CHANGED="202",J.SINGLE_CONNECTION_STAT="203",J.SPC_RECONNECTED="204",J.HEARTBEAT_REPORT="251",J.RECEIVED_PUBLISHED_USER_LIST="252",J.REMOTE_PUBLISH_STATE_CHANGED="253",J.AUDIO_LEVEL_INTERVAL="260",J.NETWORK_QUALITY="261",J.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",J.QUALITY_LIMITATION_CHANGED="263",J.LOG="264",J))(zt||{});var I=zt;var Qf="%cTRTC%c%s",Yf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Kf="display: inline",qn=class qn{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Wr&&!Ws&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(I.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Ct[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(I.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(I.JOIN_FAILED,()=>{this.startUpload()}),T.on(I.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(),5e3)}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:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(K(t.userId)&&Q(t.sdkAppId)){let{userId:r,sdkAppId:o}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:c}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:dn(),sdkAppId:String(a),userId:n,version:Me,log:c.map(l=>l.log).join(`
|
|
6
|
-
`)}),a),c.forEach(l=>l.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return jt({retryFunction:()=>Ai({url:Ei(e,Gi.LOG),body:i,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;return e.setTime(Hs()),`[${ln(e)}] <${Ct[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(Ct[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(K(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,h)=>`${l} ${this.logChunkToString(h)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};if(T.emit(I.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=Ct[i])==null?void 0:c.toLowerCase())||"info";qn.PRINT_LOG_TAG?console[a](Qf,Yf,Kf,...e):console[a](...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 Zr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Ct[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(qn,"PRINT_LOG_TAG",!(Se||he||ed));var cd=qn,R=new cd;var Zf=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s=="x"?i:i&3|8).toString(16)})},go=Zf;var dd=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!yi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let o=JSON.parse(r);if(o&&o.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(yi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!yi())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){R.warn(e)}}setItem(i,e){if(yi())try{let t={expiresIn:Date.now()+mn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!yi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(yi())try{localStorage.clear()}catch(i){R.warn(i)}}},us=new dd;var ti={};fi(ti,{HTTPS_API:()=>T_,IS_GET_CAPABILITIES_SUPPORTED:()=>kd,IS_GET_SETTINGS_SUPPORTED:()=>ei,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Md,IS_INSERTABLE_STREAM_SUPPORTED:()=>Oi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>na,IS_RTC_RTP_SENDER_SUPPORTED:()=>Co,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>oa,IS_SEI_SUPPORTED:()=>bo,IS_SPC_SUPPORTED:()=>ps,basis:()=>A_,capabilityCheck:()=>Pd,checkSystemRequirementsInternal:()=>sa,decodeSupportStatus:()=>ra,encodeSupportStatus:()=>Nd,getBrowserInfo:()=>f_,getDisplayResolution:()=>Nh,isAddTransceiverSupported:()=>mt,isBrowserSupported:()=>vd,isGetReceiversSupported:()=>Rr,isGetSendersSupported:()=>Zi,isGetTransceiversSupported:()=>Zt,isGetUserMediaSupported:()=>vh,isMediaDevicesSupported:()=>ia,isMediaSessionSupported:()=>kh,isMediaStreamTrackProcessorSupported:()=>Dd,isReplaceTrackSupported:()=>Od,isRequestVideoFrameCallbackSupported:()=>Cr,isSIMDSupported:()=>I_,isScreenCaptureApiAvailable:()=>Ao,isSelectedCandidatePair:()=>Ki,isSetParametersSupported:()=>yo,isSmallStreamAPISupported:()=>Oh,isSmallStreamSupported:()=>Ro,isStopTransceiverSupported:()=>S_,isTRTCSupported:()=>__,isUnifiedPlanDefault:()=>E_,isUsedInHttpProtocol:()=>Di,isWebAudioSupported:()=>Dh,isWebCodecSupported:()=>Mh,isWebCodecsSupported:()=>bh,isWebRTCSupported:()=>Ld,isWebTransportSupported:()=>Lh});var Id={};fi(Id,{AUDIO_LEVEL_SCALE:()=>Et,AudioCodecPipelineType:()=>Ed,AudioDecoderDowngradeState:()=>md,AudioPlayerMode:()=>gd,AudioType:()=>lh,BASIC_TYPE:()=>Qi,BannedReason:()=>Td,CONNECTION_CLOSED_REASON:()=>ud,ClientEvent:()=>ah,CodecType:()=>fh,ConnectionEvent:()=>Pt,ConnectionState:()=>ht,DECODE_FAILED_ERROR_CODE:()=>Sd,FacingMode:()=>zn,LeaveReason:()=>ph,LocalTrackEvent:()=>To,MULTI_VIDEO_DATA_TYPE:()=>wt,MediaType:()=>Pe,MediaTypeLabel:()=>e_,MonitorEventId:()=>So,MutedFlag:()=>dh,NetworkQualityValue:()=>_d,PlayerState:()=>Er,ReceiveMode:()=>mh,RemoteStreamType:()=>st,RemoteTrackEvent:()=>Eo,RoomEvent:()=>Ni,SceneNumber:()=>hd,StreamEvent:()=>ch,StreamType:()=>hh,SubscribeMediaType:()=>ld,TIMER_TYPE:()=>Yt,TRACK_ACTION:()=>fd,TRACK_KIND:()=>pd,TrackEvent:()=>Qt,UserRole:()=>Ke,UserRoleNumber:()=>Sr,VideoCodec:()=>Yi,VideoCodecPipelineType:()=>Yn,VideoContentHint:()=>hs,VideoDecoderDowngradeState:()=>Xn,VideoPlayerMode:()=>Qn,VideoType:()=>uh});var Pt=(_=>(_.TRACK_ADDED="track-added",_.TRACK_UPDATED="track-updated",_.TRACK_SUBSCRIBED="track-subscribed",_.STREAM_ADDED="stream-added",_.STREAM_REMOVED="stream-removed",_.STREAM_UPDATED="stream-updated",_.STREAM_PUBLISHED="stream-published",_.STREAM_SUBSCRIBED="stream-subscribed",_.STREAM_UNSUBSCRIBED="stream-unsubscribed",_.STATE_CHANGED="state-changed",_.ERROR="error",_.CONNECTION_STATE_CHANGED="connection-state-changed",_.FIREWALL_RESTRICTION="firewall-restriction",_.SEI_MESSAGE="sei-message",_.CLOSED="closed",_))(Pt||{}),ud=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(ud||{}),ah=(C=>(C.STREAM_ADDED="stream-added",C.STREAM_REMOVED="stream-removed",C.STREAM_UPDATED="stream-updated",C.STREAM_SUBSCRIBED="stream-subscribed",C.CONNECTION_STATE_CHANGED="connection-state-changed",C.PEER_JOIN="peer-join",C.PEER_LEAVE="peer-leave",C.MUTE_AUDIO="mute-audio",C.MUTE_VIDEO="mute-video",C.UNMUTE_AUDIO="unmute-audio",C.UNMUTE_VIDEO="unmute-video",C.CLIENT_BANNED="client-banned",C.NETWORK_QUALITY="network-quality",C.AUDIO_VOLUME="audio-volume",C.SEI_MESSAGE="sei-message",C.ERROR="error",C))(ah||{}),ch=(o=>(o.PLAYER_STATE_CHANGED="player-state-changed",o.SCREEN_SHARING_STOPPED="screen-sharing-stopped",o.CONNECTION_STATE_CHANGED="connection-state-changed",o.DEVICE_AUTO_RECOVERED="device-auto-recovered",o.ERROR="error",o))(ch||{}),To=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(To||{}),Er=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Er||{}),Ni=(F=>(F.PEER_JOIN="peer-join",F.PEER_LEAVE="peer-leave",F.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",F.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",F.BANNED="banned",F.NETWORK_QUALITY="network-quality",F.AUDIO_VOLUME="audio-volume",F.SEI_MESSAGE="sei-message",F.ERROR="error",F.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",F.REMOTE_PUBLISHED="remote-published",F.REMOTE_UNPUBLISHED="remote-unpublished",F.FIREWALL_RESTRICTION="firewall-restriction",F.HEARTBEAT_REPORT="heartbeat-report",F.CUSTOM_MESSAGE="custom-message",F.LAYER_DATA="layerData",F.FIRST_VIDEO_FRAME="first-video-frame",F.DUMP="dump",F.AUDIO_FRAME="audio-frame",F))(Ni||{}),Qt=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a.FIRST_VIDEO_FRAME="first-video-frame",a))(Qt||{}),Eo=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Eo||{}),dh=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(dh||{}),hd=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(hd||{}),Sr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Sr||{}),Ke=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Ke||{}),ht=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(ht||{}),md=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(md||{}),Xn=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Xn||{}),pd=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(pd||{}),fd=(e=>(e.ADD="add",e.REMOVE="remove",e))(fd||{}),Pe=(o=>(o[o.NULL=0]="NULL",o[o.AUDIO=1]="AUDIO",o[o.AUX_VIDEO=2]="AUX_VIDEO",o[o.BIG_VIDEO=4]="BIG_VIDEO",o[o.SMALL_VIDEO=8]="SMALL_VIDEO",o))(Pe||{}),e_={1:"audio",2:"auxVideo",4:"video"},lh=(i=>(i[i.opus=111]="opus",i))(lh||{}),uh=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(uh||{}),hh=(e=>(e.Big="big",e.Small="small",e))(hh||{}),st=(e=>(e.Main="main",e.Aux="auxiliary",e))(st||{}),wt=(o=>(o[o.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",o[o.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",o[o.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",o[o.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",o[o.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",o))(wt||{}),So=(O=>(O[O.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",O[O.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",O[O.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",O[O.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",O[O.MUTE_AUDIO=32772]="MUTE_AUDIO",O[O.MUTE_VIDEO=32773]="MUTE_VIDEO",O[O.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",O[O.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",O[O.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",O[O.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",O[O.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",O[O.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",O[O.SWITCH_CAMERA=32780]="SWITCH_CAMERA",O[O.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",O[O.REPLACE_VIDEO=32782]="REPLACE_VIDEO",O[O.REPLACE_AUDIO=32783]="REPLACE_AUDIO",O[O.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",O[O.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",O[O.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",O[O.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",O[O.JOIN=32788]="JOIN",O[O.LEAVE=32789]="LEAVE",O[O.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",O[O.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",O[O.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",O[O.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",O[O.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",O[O.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",O[O.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",O[O.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",O[O.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",O[O.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",O[O.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",O[O.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",O[O.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",O[O.PUBLISH_AUX=32805]="PUBLISH_AUX",O[O.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",O[O.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",O[O.VIDEO_ENCODER=4004]="VIDEO_ENCODER",O[O.VIDEO_DECODER=4005]="VIDEO_DECODER",O))(So||{}),_d=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(_d||{}),mh=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(mh||{}),zn=(e=>(e.user="user",e.environment="environment",e))(zn||{}),Qn=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(Qn||{}),gd=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(gd||{}),Td=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(Td||{}),ph=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(ph||{}),Et=1e8,ld=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Qi||{}),Yi=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(Yi||{}),Yn=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(Yn||{}),Ed=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(Ed||{}),fh=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(fh||{}),Sd=(f=>(f[f.SUCCESS=0]="SUCCESS",f[f.FAILED=1]="FAILED",f[f.WEBCODEC_INIT=2]="WEBCODEC_INIT",f[f.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",f[f.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",f[f.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",f[f.WASM_INIT=6]="WASM_INIT",f[f.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",f[f.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",f[f.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",f[f.TEST=10]="TEST",f[f.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",f))(Sd||{}),hs=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(hs||{}),Yt=(o=>(o.INTERVAL="interval",o.TIMEOUT="timeout",o.RAF="raf",o.RIC="ric",o.INTERVAL_IN_WORKER="intervalInWorker",o))(Yt||{});var L={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},we={AVOID_REPEATED_CALL(s){return`previous ${s.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ee(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ee(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:s,rule:i,fnName:e,value:t}){return`the min value of ${s||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:s,rule:i,fnName:e,value:t}){return`the max value of ${s||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(s){return`${s.commandDesc||s.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(s){return`SignalChannel setup failure: (errorCode: ${s.errorCode}, errorMsg: ${s.errorMsg} }).`},ERROR_MESSAGE(s){let i=`${s.type} failed`;return s.message&&(i=`${i}: ${s.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(s){return`exchange sdp failed ${s.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(s){return`'${s}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(s){return`'${s}' 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:s,code:i}){return`Failed to join room - ${s} code: ${i}`},REJOIN_ROOM_FAILED(s){return`reJoin room: ${s.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(s){return`duplicate ${s} stream publishing, please unpublish your prev ${s} 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:s,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${s}.`},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(s){return`switchRole failed, errCode: ${s.code} errMsg: ${s.message}.`},CLIENT_BANNED(s){return`client was banned because of ${s.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(s){return`startPublishCDNStream failed, errMsg: ${s.message}.`},STOP_PUBLISH_CDN_FAILED(s){return`stopPublishCDNStream failed, errMsg: ${s.message}.`},INVALID_STREAM_ID(s){return`'${s}' 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(s){return`cannot replace ${s.kind} track because stream has not ${s.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(s){return`startMixTranscode failed, errMsg: ${s.message}.`},STOP_MIX_TRANSCODE_FAILED(s){return`stopMixTranscode failed, errMsg: ${s.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:s,rule:i,fnName:e,value:t}){return`'${s||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(s){return`'${s}' 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:s,fnName:i})=>`'${s}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:s,fnName:i,type:e})=>`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:s=>`${s.media} play failed, browser exception: ${s.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(s){return`${s}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(s){return`${s.signalResponse} failed, response code is ${s.code} , errMsg: ${s.message}.`},CATCH_HANDLER_ERROR({name:s,event:i}){return`an error was caught in ${s}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:s}){return`experimental api ${s} does not exist.`},REPEAT_JOIN:s=>"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:s}){return`failed to call ${s}() because client was destroyed.`},SEI_NOT_SUPPORT:s=>`not support to sendSEIMessage${s===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:s,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${s?"size":"times"} is over ${s?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(s){return`connection aborted due to: ${s}`},API_CALL_ABORTED(s){let i;return s.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${s.userId} ${s.streamType} stream aborted, reason: remote user ${s.userId} unpublished stream.`:i=`API aborted, reason: ${s.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:s=>`'streamType' is required when 'userId' is not '*', calling ${s}()`};var _h=(s,i)=>i?`${Ht}/${s}/${i}`:`${Ht}/${s}/index.html`;var t_=()=>{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 s=localStorage==null?void 0:localStorage.getItem(Dc);if(s){s=JSON.parse(s);let i=document.createElement("script");i.type="text/javascript",i.text=s.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 P(s){let{key:i,data:e,link:t,addDocLink:r=!0}=s,o="",n="",a="";se(we[i])?o=we[i](e):K(we[i])&&(o=we[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=t_();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(se(l[i])?a=l[i](e):K(l[i])&&(a=l[i]));let h=o;return Nt()&&(c&&c[i]&&(se(c[i])?n=c[i](e):K(c[i])&&(n=c[i])),n&&(r?h=`${n}
|
|
7
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${
|
|
5
|
+
`}});var lu=li(Bi=>{"use strict";var xr=ip(),OT=sp();Bi.write=OT;Bi.parse=xr.parse;Bi.parseParams=xr.parseParams;Bi.parseFmtpConfig=xr.parseFmtpConfig;Bi.parsePayloads=xr.parsePayloads;Bi.parseRemoteCandidates=xr.parseRemoteCandidates;Bi.parseImageAttributes=xr.parseImageAttributes;Bi.parseSimulcastStreamList=xr.parseSimulcastStreamList});import i$ from"webrtc-adapter";var Wm=Ue(qe());var Ou=(P=>(P[P.INVALID_PARAMETER=4096]="INVALID_PARAMETER",P[P.INVALID_OPERATION=4097]="INVALID_OPERATION",P[P.NOT_SUPPORTED=4098]="NOT_SUPPORTED",P[P.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",P[P.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",P[P.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",P[P.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",P[P.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",P[P.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",P[P.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",P[P.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",P[P.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",P[P.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",P[P.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",P[P.CLIENT_BANNED=16448]="CLIENT_BANNED",P[P.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",P[P.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",P[P.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",P[P.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",P[P.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",P[P.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",P[P.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",P[P.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",P[P.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",P[P.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",P[P.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",P[P.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",P[P.API_CALL_ABORTED=16461]="API_CALL_ABORTED",P[P.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",P[P.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",P[P.UNKNOWN=65535]="UNKNOWN",P))(Ou||{}),S=Ou;var Kp=function(s){for(let i in S)if(S[i]===s)return i;return"UNKNOWN"},Ic=class extends Error{constructor({name:e="RtcError",message:t,code:r=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${Kp(r)} 0x${r.toString(16)}>`,d=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(d);c(this,"code");c(this,"extraCode");c(this,"message");c(this,"originMessage");c(this,"name");c(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=d,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=Ic;var ku=new Date().getTime(),Ac=0,Mu=function(s){ku=s,Ac=ku-new Date().getTime();let i=new Date;i.setTime(s),C.info(`baseTime from server: ${i} offset: ${Ac}`)},Fs=function(){return new Date().getTime()+Ac},cn=function(){let s=new Date;return s.setTime(Fs()),s.toLocaleString()},dn=function(s){let i=String(s.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${s.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var at={};ui(at,{bytes2ms:()=>Fu,convertObjectNumberToInt:()=>Zs,copyProperties:()=>Bu,deepClone:()=>lr,deepMerge:()=>Ht,delay:()=>gi,fibonacci:()=>hr,formatedTime:()=>Xu,getConstructorName:()=>Ys,getContainerFromElement:()=>qu,getEnv:()=>Uu,getInternalVersion:()=>Ju,getLoggerUrl:()=>fi,getMediaStreamTrackInfo:()=>bn,getMuteStateFromFlag:()=>_i,getNetworkType:()=>xc,getNumNetworkType:()=>ur,getReconnectionTimeout:()=>yt,getStringByteLength:()=>Ks,getTurnServer:()=>ju,getUint32Version:()=>Cn,getValueType:()=>Re,getViewListFromView:()=>zr,glog:()=>Bc,ipv4ToUint32:()=>Xr,isArray:()=>Se,isAudioWorkletSupported:()=>Wu,isBoolean:()=>fe,isConstructor:()=>jr,isEmpty:()=>qr,isFunction:()=>ae,isLangChinese:()=>Rt,isMediaStreamTrack:()=>Hu,isNumber:()=>Q,isObject:()=>$t,isOverseaSdkAppId:()=>Qs,isPlainObject:()=>tt,isPortrait:()=>An,isPromise:()=>Wi,isRemoteTrack:()=>Gu,isString:()=>K,isUndefined:()=>g,loadImage:()=>Qr,ms2bytes:()=>$u,ms2samples:()=>Vc,normalizeUrl:()=>yn,performanceNow:()=>L,promiseAny:()=>mr,samples2ms:()=>Uc,setNetworkType:()=>Sn,stringify:()=>_t,stringifyIncludeValue:()=>In,throttlePromise:()=>Rn});var wc={};ui(wc,{AUDIO_MUTE_BIT:()=>_n,AUDIO_STAT_BIT:()=>Hi,AUX_STAT_BIT:()=>nr,AUX_STREAM_MSID:()=>vc,BACKEND_ENV:()=>fn,BASE_DOC_URL:()=>Bt,BASE_HOST:()=>Lu,CAPABILITIES_KEYS:()=>En,CLASS_NAME:()=>If,CLOUD_CONSOLE_URL:()=>rf,CROSS_ROOM_BIT:()=>Nc,DATA_FREEZE_TIMING:()=>Tn,DEFAULT_ASSETS_URL:()=>ln,DOC_URL:()=>sf,DTLS_STATE_UNKNOWN:()=>Ct,ENV_NAME:()=>hi,EXCHANGE_SDP_TIMEOUT:()=>Lc,IS_WORKER:()=>Hr,IS_WORKLET:()=>Hs,KIBANA_EVENT:()=>et,LOCAL_STREAM_PUBLISH_STATE:()=>wu,LOGGER_CMD_TYPE:()=>Fi,LOGGER_DOMAIN:()=>Rc,LOGGER_DOMAIN_OVERSEA:()=>yc,LOG_LEVEL:()=>At,LOG_LEVEL_NAME:()=>Cf,MAIN_STREAM_MSID:()=>Js,MAX_RTT:()=>Xs,MICROPHONE_COMMUNICATIONS:()=>Af,MICROPHONE_DEFAULT:()=>dr,MUTE_ALL_BIT:()=>af,NAME:()=>p,NETWORK_TYPE:()=>un,NOT_SUPPORTED_H264:()=>ar,PAUSED_RETRY_COUNT:()=>cr,PEERCONNECTION_CONNECTING_TIMEOUT:()=>js,PEER_CONNECTION_STATE:()=>he,PEER_LEAVE_REASON:()=>Pc,RECOVER_CAPTURE_INTERVAL:()=>Jr,REMOTE_STREAM_TYPE_AUX:()=>Oc,REMOTE_STREAM_TYPE_MAIN:()=>Dc,RENDER_FREEZE_TIMING:()=>gf,SCHEDULE_DOMAIN:()=>pi,SCHEDULE_TIMEOUT:()=>Sf,SDP_SEMANTICS_PLAN_B:()=>Gr,SDP_SEMANTICS_UNIFIED_PLAN:()=>Gi,SECOND_HOST:()=>ef,SIGNAL_PING_PONG_INTERVAL:()=>nf,SIGNAL_PING_TIMEOUT:()=>of,SIGNAL_RECONNECTION_COUNT:()=>ff,SMALL_STAT_BIT:()=>Ws,SPEAKER_DEFAULT:()=>qs,STORAGE_EXPIRES_TIME:()=>hn,STREAM_TYPE_BIG:()=>Tf,STREAM_TYPE_SMALL:()=>Ef,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Wr,SYNC_USER_LIST_INTERVAL:()=>_f,Scene:()=>Ft,THIRD_HOST:()=>tf,TRANSPORT_DIRECTION:()=>Y,TRTC_ERROR_ASSISTANCE:()=>bc,TRTC_QUALITY_BAD:()=>hf,TRTC_QUALITY_DISCONNECTED:()=>pf,TRTC_QUALITY_EXCELLENT:()=>df,TRTC_QUALITY_GOOD:()=>lf,TRTC_QUALITY_POOR:()=>uf,TRTC_QUALITY_UNKNOWN:()=>cf,TRTC_QUALITY_VERY_BAD:()=>mf,UPDATE_OFFER_TIMEOUT:()=>Mc,VIDEO_MUTE_BIT:()=>gn,VIDEO_STAT_BIT:()=>$i,audioProfileMap:()=>mn,getRetryCount:()=>mi,getScriptDir:()=>Zp,innerVersion:()=>$s,loggerProxy:()=>Gs,screenProfileMap:()=>pn,setLoggerProxy:()=>or,setRetryCount:()=>kc,setVersion:()=>Cc,version:()=>ve,videoProfileMap:()=>ft});var $s="4.15.00.1600",ve="5.0.0";function Cc(s){ve=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));$s=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Hr=typeof importScripts!="undefined",Hs=typeof registerProcessor!="undefined",Zp=()=>{let s=Hr?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},Gs="",or=s=>Gs=s,Lu="web.sdk.qcloud.com",ef="web.sdk.tencent.cn",tf="web.sdk.cloud.tencent.cn",rf="https://console.cloud.tencent.com/trtc",Bt=`https://${Lu}/trtc/webrtc/v5/doc`,ln="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",sf=`${Bt}/zh-cn/`,Rc="https://yun.tim.qq.com",yc="https://apisgp.my-imcloud.com",bc="trtc_error_assistance",Fi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},hi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},At=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(At||{}),of=18e3,nf=2e3,un={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},hn=7*24*3600*1e3,mn={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}},ft={"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}},pn={"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}},p={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",LOADEDMETADATA:"loadedmetadata",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"},Y={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},fn={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ft=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ft||{}),$i=1,Ws=2,nr=4,Hi=8,_n=64,gn=16,af=112,Nc=128,Js="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",vc="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Dc=p.MAIN,Oc=p.AUXILIARY,cf=0,df=1,lf=2,uf=3,hf=4,mf=5,pf=6,Ct="unknown",he={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Pu=1/0;function kc(s){Pu=s}function mi(){return Pu}var ff=30,et={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"},_f=1e4,Mc=1e4,Lc=1e4,Gi="unified-plan",Gr="plan-b",ar=1028,wu=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(wu||{}),Tn=500,gf=1e3,Tf=p.BIG,Ef=p.SMALL,js=10*1e3,pi={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Sf=2e3,If={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},cr=5,dr="default",qs=dr,Af="communications",Cf=Object.keys(At),Pc=["normal leave","timeout leave","kick","role change"],Wr=10,Jr=2e3,En=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Xs=10*1e3;var Uu=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Qs=s=>Number(s)<14e8,fi=function(s,i){let e;Gs?e=Gs:e=Qs(s)?yc:Rc;let t=Math.floor(Math.random()*Vs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},zs="unknown";function xc(){if(zs!=="unknown")return zs;let{userAgent:s,connection:i}=navigator,e=(s.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t&&(zs=Vu(t,r)),zs}function Vu(s,i){if(un[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Sn(s){zs=Vu(s)}function ur(){return un[xc()]}function Bu(s,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(s,e,t)}return s}function Fu(s,i=48e3){return Uc(s/4,i)}function Uc(s,i=48e3){return s*1e3/i}function $u(s,i=48e3){return Vc(s,i)*4}function Vc(s,i=48e3){return s*i/1e3}var Bc=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Rt=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},tt=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 hr(s,i=1,e=1){return s<=1?e:hr(s-1,e,i+e)}function yt(s){return s>8?30*1e3:hr(s)*1e3}function Re(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ae=s=>typeof s=="function",g=s=>typeof s=="undefined",K=s=>typeof s=="string",Q=s=>typeof s=="number",fe=s=>typeof s=="boolean",$t=s=>Re(s)==="object",Se=s=>Re(s)==="array",Hu=s=>Re(s)==="MediaStreamTrack".toLowerCase(),Gu=s=>s.isRemote,Wi=s=>Re(s)==="promise",jr=s=>ae(s)&&s.prototype.constructor===s,Ys=s=>jr(s)?s.prototype.constructor.name:"",Wu=typeof AudioWorkletNode!="undefined";function mr(s){return new Promise((i,e)=>{let t=[];s.forEach(r=>{r.then(i).catch(o=>{t.push(o),t.length===s.length&&e(t)})})})}function L(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var xu=s=>+s<10?`0${s}`:s,Ju=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=xu(e[1])+xu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Rf=Object.prototype.hasOwnProperty,{toString:cE}=Object.prototype;function qr(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(tt(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(Rf.call(s,i))return!1;return!0}}return!1}function _i(s,i){return{userId:i,hasAudio:!!(s&Hi),hasVideo:!!(s&$i),hasAuxiliary:!!(s&nr),hasSmall:!!(s&Ws),audioMuted:!!(s&_n),videoMuted:!!(s&gn),audioAvailable:!!(s&Hi)&&!(s&_n),videoAvailable:!!(s&$i)&&!(s&gn)}}function ju(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!g(s.username)&&!g(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",g(s.credentialType)||(i.credentialType=s.credentialType)),i}function Xr(s,i=!0){if(!K(s))return 0;let e=s.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(s,i,e,t){if(!($t(s)&&$t(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,d=o.length;a<d;a++)if(n=o[a],!(g(i[n])||e&&e.includes(n)))if($t(s[n])&&$t(i[n]))r+=Ht(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=lr(i[n]),r+=1)}return r};function lr(s){if(Se(s)){let i=[];return s.forEach((e,t)=>{i[t]=lr(e)}),i}if($t(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=lr(s[e])}),i}return s}var zr=s=>{let i=[];if(Se(s))i=[...s];else if(K(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},qu=s=>K(s)?document.getElementById(s):s,yf=s=>{let i=d=>d<10?`0${d}`:`${d}`,e=s.getFullYear(),t=s.getMonth()+1,r=s.getDate(),o=i(s.getHours()),n=i(s.getMinutes()),a=i(s.getSeconds());return`${e}/${t}/${r} ${o}:${n}:${a}`},Xu=()=>yf(new Date);function _t(s,{keysToInclude:i,keysToExclude:e}){try{if(Se(s))return`[${s.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!tt(s)||!Se(i)&&!Se(e))return JSON.stringify(s);let t={},r=new Set(i),o=new Set(e);return Object.keys(s).forEach(n=>{(o.size===0&&r.has(n)||r.size===0&&!o.has(n))&&(t[n]=tt(s[n])||Se(s[n])?JSON.parse(_t(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function In(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),_t(s,{keysToInclude:e})}function Ks(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var An=()=>{var s,i,e,t;return(s=window.screen)!=null&&s.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},Qr=s=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(K(s))t=new Image,t.crossOrigin="anonymous",t.src=s;else if(t=s,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),Cn=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Zs=s=>(Object.keys(s).forEach(i=>{Q(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(tt(s[i])||Se(s[i]))&&Zs(s[i])}),s);function gi(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function Rn(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function yn(s){return s.replace(/(^|[^:])\/{2,}/g,"$1/")}function bn(s){var i;try{let{width:e,height:t,frameRate:r,sampleRate:o,sampleSize:n,channelCount:a}=(i=s.getSettings)==null?void 0:i.call(s),d=s.kind===p.AUDIO?`${o}x${n}@${a}`:`${e}x${t}@${r}`,l=s.stats?` stats: ${JSON.stringify(s.stats).replaceAll('"',"")}`:"";return`${s.id} ${s.readyState} muted:${s.muted} ${s.kind} ${s.label} ${d}${l}`}catch(e){return""}}function Ti({url:s,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((o,n)=>{if("fetch"in window)return fetch(s,{method:e,body:i,priority:r}).then(d=>d.text()).then(d=>{try{o({data:JSON.parse(d)})}catch(l){o({data:d})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let d=JSON.parse(a.response);o({data:d})}catch(d){o({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,s,!0),a.send(i)})}function Fc(s){return f(this,null,function*(){let i=L(),e=JSON.stringify(s);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return C.debug(`compressJSON ${e.length} -> ${a.byteLength} ${L()-i}ms`),a}catch(t){return e}})}var bf=Object.prototype.hasOwnProperty;var Gt=s=>typeof s=="function",Ei=s=>typeof s=="undefined";var Nn=s=>typeof s=="boolean";var $c=s=>s.isRemote;var Nf=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 zu(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Nf(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(bf.call(s,i))return!1;return!0}}return!1}var vf=0,Df=1,Qu=2;function Of({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:d=5,timeout:l=1e3}=i,u=0,h=-1,m=vf,_=(I,R)=>f(this,null,function*(){let D=n||this;try{let W=yield s.apply(D,a);u>0&&o&&o.call(this,u),u=0,I(W)}catch(W){let te=()=>{clearTimeout(h),u=0,m=Qu,R(W)},on=()=>{m!==Qu&&u<(Gt(d)?d():d)?(u++,m=Df,Gt(t)&&t.call(this,u,te),h=window.setTimeout(()=>{h=-1,_(I,R)},Gt(l)?l(u):l)):(te(),Gt(r)&&r.call(this,W))};Gt(e)?e.call(this,{error:W,retry:on,reject:R,retryFuncArgs:a,retriedCount:u}):on()}});return new Promise(_)}}var Wt=Of;var Yr=class{constructor(i){c(this,"userId");c(this,"remoteUserId");c(this,"id");c(this,"sdkAppId");c(this,"type");c(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Nn(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}`:""}]`),C.log(i,e,Ei(this.userId)||zu(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 cs={};ui(cs,{ANDROID_VERSION:()=>Wc,CHROME_MAJOR_VERSION:()=>ct,CHROME_VERSION:()=>Wn,EDGE_VERSION:()=>Dn,EDG_MAJOR_VERSION:()=>Jc,EDG_VERSION:()=>On,FIREFOX_MAJOR_VERSION:()=>eo,FIREFOX_VERSION:()=>vn,HUAWEI_VERSION:()=>Fn,IE_VERSION:()=>wf,IOS_MAIN_VERSION:()=>dt,IOS_VERSION:()=>jt,IPADQQB_VERSION:()=>Vn,IS_ANDROID:()=>ue,IS_ANDROID_WEBVIEW:()=>Bf,IS_ANY_SAFARI:()=>ji,IS_CHROME:()=>as,IS_CHROME_OS:()=>jc,IS_CHROMIUM_BASE:()=>Xe,IS_DESKTOP_IOS_CHROME:()=>td,IS_EDG:()=>ts,IS_EDGE:()=>es,IS_ELECTRON:()=>Uf,IS_FIREFOX:()=>se,IS_HEADLESS_CHROME:()=>Yc,IS_HONOR:()=>zc,IS_HUAWEI:()=>Xc,IS_HUAWEIBROWSER:()=>co,IS_IE:()=>eh,IS_IE8:()=>Pf,IS_IOS:()=>ge,IS_IOS_13_OR_14:()=>ed,IS_IOS_15_1:()=>Zc,IS_IOS_CHROME:()=>th,IS_IPAD:()=>Zr,IS_IPADQQB:()=>oo,IS_IPAD_PRO:()=>Gc,IS_IPHONE:()=>Ji,IS_IPOD:()=>Zu,IS_LINUX:()=>no,IS_LOCAL:()=>Ot,IS_MAC:()=>Dt,IS_MACQQB:()=>so,IS_MIBROWSER:()=>ao,IS_MQQB:()=>os,IS_NATIVE_ANDROID:()=>Lf,IS_OLD_ANDROID:()=>Mf,IS_OPENHARMONY:()=>Qc,IS_OPPOBROWSER:()=>uo,IS_SAFARI:()=>Oe,IS_SAFARI_15_1:()=>Ff,IS_SAMSUNGBROWSER:()=>lo,IS_SOGOU:()=>io,IS_SOGOUM:()=>to,IS_TBS:()=>vt,IS_UCBROWSER:()=>qc,IS_VIVOBROWSER:()=>ho,IS_WECHAT:()=>rs,IS_WIN:()=>pr,IS_WQQB:()=>ro,IS_WX:()=>xf,IS_X5MQQB:()=>ss,IS_XWEB:()=>is,MACQQB_VERSION:()=>Un,MI_VERSION:()=>Bn,MQQB_VERSION:()=>Kr,OPENHARMONY_VERSION:()=>Vf,OPPO_VERSION:()=>Hn,SAFARI_VERSION:()=>Si,SAMSUNG_VERSION:()=>$n,SOGOUM_VERSION:()=>kn,SOGOU_VERSION:()=>Mn,TBS_VERSION:()=>Ln,UA_DATA_STRING:()=>bt,USER_AGENT:()=>Nt,VIVO_VERSION:()=>Gn,WECHAT_VERSION:()=>wn,WQQB_VERSION:()=>xn,XWEB_VERSION:()=>Pn,browserInfo:()=>Jt,getBrowserInfo:()=>ih,getChromeMajorVersion:()=>ns,getDeviceModel:()=>fr,getGPUInfo:()=>rd,getOSName:()=>Jn,getOSNumber:()=>po,getOSString:()=>Ai,getOSType:()=>$f,getTerminalType:()=>sd,getUserAgentData:()=>mo,isLocalStorageEnabled:()=>Ii,isMobile:()=>id,isVersionSmallerThan:()=>Kc});var Nt=typeof navigator=="undefined"?"":navigator.userAgent,j=s=>new RegExp(s,"i").test(Nt),ye=s=>{if(j(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=Nt.match(i);if(e&&e[1])return e[1]}return""},Hc=s=>{if(j(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=Nt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Yu=/AppleWebKit\/([\d.]+)/i.exec(Nt),kf=Yu?parseFloat(Yu[1]):NaN,Zr=j("iPad"),Gc=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&j("Macintosh"),Ji=j("iPhone")&&!Zr,Zu=j("iPod"),ge=Ji||Zr||Zu||Gc,ue=j("Android"),Wc=function(){if(ue){let s=Nt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(s){let i=s[1]&&parseFloat(s[1]),e=s[2]&&parseFloat(s[2]);if(i&&e)return parseFloat(`${s[1]}.${s[2]}`);if(i)return i}}return NaN}(),Mf=ue&&j("webkit")&&Wc<2.3,Lf=ue&&Wc<5&&kf<537,se=j("Firefox"),vn=ye("Firefox"),eo=Hc("Firefox"),es=j("Edge"),Dn=ye("Edge"),ts=j("Edg"),On=ye("Edg"),Jc=Hc("Edg"),to=j("SogouMobileBrowser"),kn=ye("SogouMobileBrowser"),io=j("MetaSr\\s"),Mn=ye("MetaSr\\s"),vt=j("TBS"),Ln=ye("TBS"),is=j("XWEB"),Pn=ye("XWEB"),Pf=j("MSIE\\s8\\.0"),eh=j("MSIE\\/\\d+"),wf=function(){if(eh){let s=/MSIE\s(\d+)\.\d/.exec(Nt),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(Nt)&&/rv:11.0/.test(Nt)&&(i=11),i}return NaN}(),rs=j("(micromessenger|webbrowser)"),wn=ye("MicroMessenger"),ss=!vt&&j("MQQBrowser")&&j("COVC"),os=!vt&&j("MQQBrowser")&&!j("COVC"),Kr=os||ss?ye("MQQBrowser"):"",ro=!vt&&j(" QQBrowser"),xn=ye(" QQBrowser"),so=!vt&&j("QQBrowserLite"),Un=ye("QQBrowserLite"),oo=!vt&&j("MQBHD"),Vn=ye("MQBHD"),pr=j("Windows"),Dt=!ge&&j("MAC OS X"),no=!ue&&j("Linux"),jc=j("CrOS"),xf=j("MicroMessenger"),qc=j("UCBrowser"),Uf=j("Electron"),ao=j("MiuiBrowser"),Bn=ye("MiuiBrowser"),co=j("HuaweiBrowser"),Xc=j("Huawei")||j("HUAWEI"),zc=j("Honor")||j("HONOR"),Fn=ye("HuaweiBrowser"),lo=j("SamsungBrowser"),$n=ye("SamsungBrowser"),uo=j("HeyTapBrowser"),Hn=ye("HeyTapBrowser"),ho=j("VivoBrowser"),Gn=ye("VivoBrowser"),Qc=j("OpenHarmony"),Vf=ye("OpenHarmony"),ns=()=>Hc("Chrome"),Xe=j("Chrome"),as=!es&&!io&&!to&&!vt&&!is&&!ts&&!ro&&!ao&&!co&&!lo&&!uo&&!ho&&Xe,Yc=j("HeadlessChrome"),ct=ns(),Wn=ye("Chrome"),Oe=!Xe&&!os&&!ss&&!so&&!oo&&j("Safari"),ji=Oe||ge,Si=ye("Version"),Bf=/Android.*(wv|.0.0.0)/.test(Nt),jt=(()=>{if(Gc)return Si;if(ge){let s=Nt.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})();function Kc(s,i){let e=s.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let o=e[r]||0,n=t[r]||0;if(o<n)return!0;if(o>n)return!1}return!1}var dt=Number(jt.split(".")[0]),Ff=Si==="15.1",Zc=jt==="15.1",ed=(()=>{let s=Number(jt.split(".")[0]);return s===14||s===13})(),th=j("CriOS"),td=th&&Si==="11.1.1",Ot=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ii=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),Jt=ih();function ih(){let s=new Map([[se,["Firefox",vn]],[ts,["Edg",On]],[as,["Chrome",Wn]],[Oe,["Safari",Si]],[vt,["TBS",Ln]],[is,["XWEB",Pn]],[rs&&Ji,["WeChat",wn]],[ro,["QQ(Win)",xn]],[os,["QQ(Mobile)",Kr]],[ss,["QQ(Mobile X5)",Kr]],[so,["QQ(Mac)",Un]],[oo,["QQ(iPad)",Vn]],[ao,["MI",Bn]],[co,["HW",Fn]],[lo,["Samsung",$n]],[uo,["OPPO",Hn]],[ho,["VIVO",Gn]],[es,["EDGE",Dn]],[to,["SogouMobile",kn]],[io,["Sogou",Mn]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var oe=null;function id(){return oe&&typeof oe.mobile=="boolean"?oe.mobile:ue||ge||Ji||Zr||Qc}var bt="";function mo(){return f(this,null,function*(){if(oe)return oe;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return oe=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),oe&&!bt&&(bt=`UAData: ${oe.platform}/${oe.platformVersion}`,oe.architecture&&oe.bitness&&(bt+=` ${oe.architecture}/${oe.bitness}`),oe.mobile&&(bt+=" mobile"),oe.model&&(bt+=` model: ${oe.model.replace(/\s+/g,"/")}`),oe.fullVersionList&&(bt+=` ${oe.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),oe}catch(s){return null}})}function rd(){try{let s=document.createElement("canvas"),i=s.getContext("webgl")||s.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(s){return""}}function fr(){return(oe==null?void 0:oe.model)||""}var Ku=new Map([[ue,"Android"],[ge,"iOS"],[pr,"Windows"],[Dt,"MacOS"],[no,"Linux"],[jc,"ChromeOS"]]),Jn=function(){return Ku.get(!0)?Ku.get(!0):oe?oe.platform:"unknown"};function po(){return pr?1:ue?2:Dt?3:ge?4:no?5:jc?6:0}var Ai=()=>{let s=Jn();return s+=`/${Jt.name}/${Oe?Jt.version:Jt.version.split(".")[0]}`,oe!=null&&oe.platformVersion&&(s+=`/${oe.platformVersion}`),oe!=null&&oe.architecture&&(s+=`/${oe.architecture}`),s};function sd(){return ue?4:Ji?2:Zr?3:Dt?12:pr?5:no?13:Qc?22:1}function $f(){return ue?"Android":Ji?"iPhone":Zr?"iPad":Dt?"Mac":pr?"Windows":no?"Linux":"unknown"}var rh=Ue(qe(),1),Hf=new rh.default,E=Hf;var Ci=(J=>(J.ROOM_DESTROY="1",J.JOIN_START="21",J.JOIN_SCHEDULE_SUCCESS="22",J.JOIN_SIGNAL_CONNECTION_START="23",J.JOIN_SIGNAL_CONNECTION_END="24",J.JOIN_SEND_CMD="25",J.JOIN_RECEIVED_CMD_RES="26",J.JOIN_SUCCESS="27",J.JOIN_FAILED="28",J.LEAVE_START="51",J.LEAVE_SEND_CMD="52",J.LEAVE_SUCCESS="53",J.PUBLISH_START="61",J.SEND_FIRST_VIDEO_FRAME="62",J.PUBLISH_FAILED="63",J.SUBSCRIBE_START="81",J.SUBSCRIBE_SUCCESS="82",J.SUBSCRIBE_FAILED="84",J.UNSUBSCRIBE_SUCCESS="83",J.LOCAL_TRACK_CAPTURE_START="101",J.LOCAL_TRACK_CAPTURE_SUCCESS="102",J.LOCAL_TRACK_CAPTURE_FAILED="103",J.LOCAL_TRACK_PUBLISHED="104",J.LOCAL_TRACK_UNPUBLISHED="105",J.LOCAL_TRACK_REPLACED="106",J.SWITCH_DEVICE_SUCCESS="107",J.TRACK_MUTED="108",J.TRACK_UNMUTED="109",J.REMOTE_TRACK_SUBSCRIBED="110",J.REMOTE_TRACK_UNSUBSCRIBED="111",J.LOCAL_TRACK_RECAPTURE="112",J.PLAY_TRACK_START="151",J.PLAYER_STATE_CHANGED="152",J.VIDEO_LOADED_DATA="153",J.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",J.SIGNAL_CONNECTION_STATE_CHANGED="201",J.PEER_CONNECTION_STATE_CHANGED="202",J.SINGLE_CONNECTION_STAT="203",J.SPC_RECONNECTED="204",J.HEARTBEAT_REPORT="251",J.RECEIVED_PUBLISHED_USER_LIST="252",J.REMOTE_PUBLISH_STATE_CHANGED="253",J.AUDIO_LEVEL_INTERVAL="260",J.NETWORK_QUALITY="261",J.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",J.QUALITY_LIMITATION_CHANGED="263",J.LOG="264",J))(Ci||{});var T=Ci;var Gf="%cTRTC%c%s",Wf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Jf="display: inline",jn=class jn{constructor(){c(this,"_isEnableUploadLog",!0);c(this,"_localJoinedUser",new Map);c(this,"_queue",[]);c(this,"_timeoutId",-1);c(this,"_logLevel",1);c(this,"_logLevelToUpload",2);!Hr&&!Hs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){E.on(T.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&At[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),E.on(T.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),E.once(T.JOIN_FAILED,()=>{this.startUpload()}),E.on(T.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(),5e3)}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:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(K(t.userId)&&Q(t.sdkAppId)){let{userId:r,sdkAppId:o}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(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 r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:d}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:cn(),sdkAppId:String(a),userId:n,version:ve,log:d.map(l=>l.log).join(`
|
|
6
|
+
`)}),a),d.forEach(l=>l.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Wt({retryFunction:()=>Ti({url:fi(e,Fi.LOG),body:i,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;return e.setTime(Fs()),`[${dn(e)}] <${At[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){g(At[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(K(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,o){var d;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,u)=>`${l} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};if(E.emit(T.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((d=At[i])==null?void 0:d.toLowerCase())||"info";jn.PRINT_LOG_TAG?console[a](Gf,Wf,Jf,...e):console[a](...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 Yr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;At[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};c(jn,"PRINT_LOG_TAG",!(ge||ue||Yc));var od=jn,C=new od;var jf=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s=="x"?i:i&3|8).toString(16)})},fo=jf;var nd=class{constructor(){c(this,"_prefix","TRTC");c(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Ii())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let o=JSON.parse(r);if(o&&o.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(Ii())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){C.warn(i)}}getItem(i){if(!Ii())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){C.warn(e)}}setItem(i,e){if(Ii())try{let t={expiresIn:Date.now()+hn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){C.warn(t)}}deleteItem(i){if(!Ii())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return C.warn(e),!1}}clear(){if(Ii())try{localStorage.clear()}catch(i){C.warn(i)}}},ds=new nd;var Yt={};ui(Yt,{HTTPS_API:()=>u_,IS_GET_CAPABILITIES_SUPPORTED:()=>Dd,IS_GET_SETTINGS_SUPPORTED:()=>Qt,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>vd,IS_INSERTABLE_STREAM_SUPPORTED:()=>Ni,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>oa,IS_RTC_RTP_SENDER_SUPPORTED:()=>Ao,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>sa,IS_SEI_SUPPORTED:()=>Ro,IS_SPC_SUPPORTED:()=>hs,basis:()=>f_,capabilityCheck:()=>kd,checkSystemRequirementsInternal:()=>ra,decodeSupportStatus:()=>ia,encodeSupportStatus:()=>Rd,getBrowserInfo:()=>c_,getDisplayResolution:()=>Rh,isAddTransceiverSupported:()=>ut,isBrowserSupported:()=>yd,isGetReceiversSupported:()=>Ir,isGetSendersSupported:()=>Qi,isGetTransceiversSupported:()=>zt,isGetUserMediaSupported:()=>yh,isMediaDevicesSupported:()=>ta,isMediaSessionSupported:()=>Dh,isMediaStreamTrackProcessorSupported:()=>bd,isReplaceTrackSupported:()=>Nd,isRequestVideoFrameCallbackSupported:()=>Ar,isSIMDSupported:()=>p_,isScreenCaptureApiAvailable:()=>So,isSelectedCandidatePair:()=>zi,isSetParametersSupported:()=>Co,isSmallStreamAPISupported:()=>Nh,isSmallStreamSupported:()=>Io,isStopTransceiverSupported:()=>m_,isTRTCSupported:()=>d_,isUnifiedPlanDefault:()=>h_,isUsedInHttpProtocol:()=>bi,isWebAudioSupported:()=>bh,isWebCodecSupported:()=>vh,isWebCodecsSupported:()=>Ch,isWebRTCSupported:()=>Od,isWebTransportSupported:()=>Oh});var Td={};ui(Td,{AUDIO_LEVEL_SCALE:()=>gt,AudioCodecPipelineType:()=>_d,AudioDecoderDowngradeState:()=>ld,AudioPlayerMode:()=>pd,AudioType:()=>ah,BASIC_TYPE:()=>Tr,BannedReason:()=>fd,CONNECTION_CLOSED_REASON:()=>cd,ClientEvent:()=>sh,CodecType:()=>hh,ConnectionEvent:()=>kt,ConnectionState:()=>lt,DECODE_FAILED_ERROR_CODE:()=>gd,FacingMode:()=>Xn,LeaveReason:()=>uh,LocalTrackEvent:()=>_o,MULTI_VIDEO_DATA_TYPE:()=>Mt,MediaType:()=>ke,MediaTypeLabel:()=>qf,MonitorEventId:()=>To,MutedFlag:()=>nh,NetworkQualityValue:()=>md,PlayerState:()=>_r,ReceiveMode:()=>lh,RemoteStreamType:()=>it,RemoteTrackEvent:()=>go,RoomEvent:()=>qi,SceneNumber:()=>dd,StreamEvent:()=>oh,StreamType:()=>dh,SubscribeMediaType:()=>ad,TIMER_TYPE:()=>qt,TRACK_ACTION:()=>hd,TRACK_KIND:()=>ud,TrackEvent:()=>Ri,UserRole:()=>ze,UserRoleNumber:()=>gr,VideoCodec:()=>Xi,VideoCodecPipelineType:()=>Qn,VideoContentHint:()=>ls,VideoDecoderDowngradeState:()=>qn,VideoPlayerMode:()=>zn,VideoType:()=>ch});var kt=(R=>(R.TRACK_ADDED="track-added",R.TRACK_UPDATED="track-updated",R.TRACK_SUBSCRIBED="track-subscribed",R.STREAM_ADDED="stream-added",R.STREAM_REMOVED="stream-removed",R.STREAM_UPDATED="stream-updated",R.STREAM_PUBLISHED="stream-published",R.STREAM_SUBSCRIBED="stream-subscribed",R.STREAM_UNSUBSCRIBED="stream-unsubscribed",R.STATE_CHANGED="state-changed",R.ERROR="error",R.CONNECTION_STATE_CHANGED="connection-state-changed",R.FIREWALL_RESTRICTION="firewall-restriction",R.SEI_MESSAGE="sei-message",R.CLOSED="closed",R))(kt||{}),cd=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(cd||{}),sh=(D=>(D.STREAM_ADDED="stream-added",D.STREAM_REMOVED="stream-removed",D.STREAM_UPDATED="stream-updated",D.STREAM_SUBSCRIBED="stream-subscribed",D.CONNECTION_STATE_CHANGED="connection-state-changed",D.PEER_JOIN="peer-join",D.PEER_LEAVE="peer-leave",D.MUTE_AUDIO="mute-audio",D.MUTE_VIDEO="mute-video",D.UNMUTE_AUDIO="unmute-audio",D.UNMUTE_VIDEO="unmute-video",D.CLIENT_BANNED="client-banned",D.NETWORK_QUALITY="network-quality",D.AUDIO_VOLUME="audio-volume",D.SEI_MESSAGE="sei-message",D.ERROR="error",D))(sh||{}),oh=(o=>(o.PLAYER_STATE_CHANGED="player-state-changed",o.SCREEN_SHARING_STOPPED="screen-sharing-stopped",o.CONNECTION_STATE_CHANGED="connection-state-changed",o.DEVICE_AUTO_RECOVERED="device-auto-recovered",o.ERROR="error",o))(oh||{}),_o=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(_o||{}),_r=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(_r||{}),qi=(te=>(te.PEER_JOIN="peer-join",te.PEER_LEAVE="peer-leave",te.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",te.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",te.BANNED="banned",te.NETWORK_QUALITY="network-quality",te.AUDIO_VOLUME="audio-volume",te.SEI_MESSAGE="sei-message",te.ERROR="error",te.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",te.REMOTE_PUBLISHED="remote-published",te.REMOTE_UNPUBLISHED="remote-unpublished",te.FIREWALL_RESTRICTION="firewall-restriction",te.HEARTBEAT_REPORT="heartbeat-report",te.CUSTOM_MESSAGE="custom-message",te.LAYER_DATA="layerData",te.FIRST_VIDEO_FRAME="first-video-frame",te.DUMP="dump",te))(qi||{}),Ri=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a.FIRST_VIDEO_FRAME="first-video-frame",a))(Ri||{}),go=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(go||{}),nh=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(nh||{}),dd=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(dd||{}),gr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(gr||{}),ze=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(ze||{}),lt=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(lt||{}),ld=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(ld||{}),qn=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(qn||{}),ud=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(ud||{}),hd=(e=>(e.ADD="add",e.REMOVE="remove",e))(hd||{}),ke=(o=>(o[o.NULL=0]="NULL",o[o.AUDIO=1]="AUDIO",o[o.AUX_VIDEO=2]="AUX_VIDEO",o[o.BIG_VIDEO=4]="BIG_VIDEO",o[o.SMALL_VIDEO=8]="SMALL_VIDEO",o))(ke||{}),qf={1:"audio",2:"auxVideo",4:"video"},ah=(i=>(i[i.opus=111]="opus",i))(ah||{}),ch=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(ch||{}),dh=(e=>(e.Big="big",e.Small="small",e))(dh||{}),it=(e=>(e.Main="main",e.Aux="auxiliary",e))(it||{}),Mt=(o=>(o[o.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",o[o.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",o[o.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",o[o.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",o[o.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",o))(Mt||{}),To=(O=>(O[O.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",O[O.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",O[O.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",O[O.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",O[O.MUTE_AUDIO=32772]="MUTE_AUDIO",O[O.MUTE_VIDEO=32773]="MUTE_VIDEO",O[O.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",O[O.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",O[O.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",O[O.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",O[O.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",O[O.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",O[O.SWITCH_CAMERA=32780]="SWITCH_CAMERA",O[O.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",O[O.REPLACE_VIDEO=32782]="REPLACE_VIDEO",O[O.REPLACE_AUDIO=32783]="REPLACE_AUDIO",O[O.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",O[O.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",O[O.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",O[O.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",O[O.JOIN=32788]="JOIN",O[O.LEAVE=32789]="LEAVE",O[O.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",O[O.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",O[O.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",O[O.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",O[O.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",O[O.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",O[O.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",O[O.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",O[O.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",O[O.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",O[O.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",O[O.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",O[O.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",O[O.PUBLISH_AUX=32805]="PUBLISH_AUX",O[O.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",O[O.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",O[O.VIDEO_ENCODER=4004]="VIDEO_ENCODER",O[O.VIDEO_DECODER=4005]="VIDEO_DECODER",O))(To||{}),md=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(md||{}),lh=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(lh||{}),Xn=(e=>(e.user="user",e.environment="environment",e))(Xn||{}),zn=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(zn||{}),pd=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(pd||{}),fd=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(fd||{}),uh=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(uh||{}),gt=1e8,ad=class{constructor(){c(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Tr=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Tr||{}),Xi=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(Xi||{}),Qn=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(Qn||{}),_d=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(_d||{}),hh=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(hh||{}),gd=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.FAILED=1]="FAILED",m[m.WEBCODEC_INIT=2]="WEBCODEC_INIT",m[m.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",m[m.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",m[m.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",m[m.WASM_INIT=6]="WASM_INIT",m[m.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",m[m.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",m[m.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",m[m.TEST=10]="TEST",m[m.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",m))(gd||{}),ls=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(ls||{}),qt=(o=>(o.INTERVAL="interval",o.TIMEOUT="timeout",o.RAF="raf",o.RIC="ric",o.INTERVAL_IN_WORKER="intervalInWorker",o))(qt||{});var x={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Me={AVOID_REPEATED_CALL(s){return`previous ${s.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:s,rule:i,fnName:e,value:t}){return`the min value of ${s||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:s,rule:i,fnName:e,value:t}){return`the max value of ${s||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(s){return`${s.commandDesc||s.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(s){return`SignalChannel setup failure: (errorCode: ${s.errorCode}, errorMsg: ${s.errorMsg} }).`},ERROR_MESSAGE(s){let i=`${s.type} failed`;return s.message&&(i=`${i}: ${s.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(s){return`exchange sdp failed ${s.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(s){return`'${s}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(s){return`'${s}' 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:s,code:i}){return`Failed to join room - ${s} code: ${i}`},REJOIN_ROOM_FAILED(s){return`reJoin room: ${s.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(s){return`duplicate ${s} stream publishing, please unpublish your prev ${s} 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:s,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${s}.`},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(s){return`switchRole failed, errCode: ${s.code} errMsg: ${s.message}.`},CLIENT_BANNED(s){return`client was banned because of ${s.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(s){return`startPublishCDNStream failed, errMsg: ${s.message}.`},STOP_PUBLISH_CDN_FAILED(s){return`stopPublishCDNStream failed, errMsg: ${s.message}.`},INVALID_STREAM_ID(s){return`'${s}' 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(s){return`cannot replace ${s.kind} track because stream has not ${s.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(s){return`startMixTranscode failed, errMsg: ${s.message}.`},STOP_MIX_TRANSCODE_FAILED(s){return`stopMixTranscode failed, errMsg: ${s.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:s,rule:i,fnName:e,value:t}){return`'${s||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(s){return`'${s}' 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:s,fnName:i})=>`'${s}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:s,fnName:i,type:e})=>`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:s=>`${s.media} play failed, browser exception: ${s.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(s){return`${s}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(s){return`${s.signalResponse} failed, response code is ${s.code} , errMsg: ${s.message}.`},CATCH_HANDLER_ERROR({name:s,event:i}){return`an error was caught in ${s}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:s}){return`experimental api ${s} does not exist.`},REPEAT_JOIN:s=>"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:s}){return`failed to call ${s}() because client was destroyed.`},SEI_NOT_SUPPORT:s=>`not support to sendSEIMessage${s===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:s,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${s?"size":"times"} is over ${s?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(s){return`connection aborted due to: ${s}`},API_CALL_ABORTED(s){let i;return s.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${s.userId} ${s.streamType} stream aborted, reason: remote user ${s.userId} unpublished stream.`:i=`API aborted, reason: ${s.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:s=>`'streamType' is required when 'userId' is not '*', calling ${s}()`};var mh=(s,i)=>i?`${Bt}/${s}/${i}`:`${Bt}/${s}/index.html`;var Xf=()=>{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 s=localStorage==null?void 0:localStorage.getItem(bc);if(s){s=JSON.parse(s);let i=document.createElement("script");i.type="text/javascript",i.text=s.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 U(s){let{key:i,data:e,link:t,addDocLink:r=!0}=s,o="",n="",a="";ae(Me[i])?o=Me[i](e):K(Me[i])&&(o=Me[i]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:l}=Xf();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ae(l[i])?a=l[i](e):K(l[i])&&(a=l[i]));let u=o;return Rt()&&(d&&d[i]&&(ae(d[i])?n=d[i](e):K(d[i])&&(n=d[i])),n&&(r?u=`${n}
|
|
7
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${mh("zh-cn",a)}
|
|
8
8
|
|
|
9
|
-
`:
|
|
9
|
+
`:u=`${n}
|
|
10
10
|
|
|
11
|
-
`,
|
|
12
|
-
Refer to: ${
|
|
13
|
-
`),h}var bd=Be(Ch(),1);var u_=1,h_=0,Zn=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",R.createLogger({id:"kv"}));i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===m.AUDIO?501700:511700,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===m.AUDIO?501700:511700,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Cn(this.version||Me),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(([r,o])=>({uint32_item_key:r,uint32_item_value:o}))}))};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 o;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 r=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(Q(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:u_,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(Q(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:h_,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},ea=(U=>(U[U.enterRoom=500700]="enterRoom",U[U.exitRoom=500701]="exitRoom",U[U.switchRole=500702]="switchRole",U[U.destroy=500703]="destroy",U[U.startLocalAudio=500704]="startLocalAudio",U[U.updateLocalAudio=500705]="updateLocalAudio",U[U.stopLocalAudio=500706]="stopLocalAudio",U[U.startLocalVideo=500707]="startLocalVideo",U[U.updateLocalVideo=500708]="updateLocalVideo",U[U.stopLocalVideo=500709]="stopLocalVideo",U[U.startScreenShare=500710]="startScreenShare",U[U.updateScreenShare=500711]="updateScreenShare",U[U.stopScreenShare=500712]="stopScreenShare",U[U.startRemoteVideo=500713]="startRemoteVideo",U[U.updateRemoteVideo=500714]="updateRemoteVideo",U[U.stopRemoteVideo=500715]="stopRemoteVideo",U[U.muteRemoteAudio=500716]="muteRemoteAudio",U[U.setRemoteAudioVolume=500717]="setRemoteAudioVolume",U[U.use=500718]="use",U[U.sendSEIMessage=5e5]="sendSEIMessage",U[U.sendCustomMessage=500001]="sendCustomMessage",U))(ea||{}),Rd=(l=>(l[l.AudioMixer=550700]="AudioMixer",l[l.AIDenoiser=551700]="AIDenoiser",l[l.VirtualBackground=570700]="VirtualBackground",l[l.Beauty=571700]="Beauty",l[l.Watermark=572700]="Watermark",l[l.BasicBeauty=574700]="BasicBeauty",l[l.CDNStreaming=590700]="CDNStreaming",l[l.DeviceDetector=591700]="DeviceDetector",l[l.Debug=592700]="Debug",l))(Rd||{}),Cd=(l=>(l[l.AudioMixer=550701]="AudioMixer",l[l.AIDenoiser=551701]="AIDenoiser",l[l.VirtualBackground=570701]="VirtualBackground",l[l.Beauty=571701]="Beauty",l[l.Watermark=572701]="Watermark",l[l.BasicBeauty=574701]="BasicBeauty",l[l.CDNStreaming=590701]="CDNStreaming",l[l.DeviceDetector=591701]="DeviceDetector",l[l.Debug=592701]="Debug",l))(Cd||{}),yd=(l=>(l[l.AudioMixer=550702]="AudioMixer",l[l.AIDenoiser=551702]="AIDenoiser",l[l.VirtualBackground=570702]="VirtualBackground",l[l.Beauty=571702]="Beauty",l[l.Watermark=572702]="Watermark",l[l.BasicBeauty=574702]="BasicBeauty",l[l.CDNStreaming=590702]="CDNStreaming",l[l.DeviceDetector=591702]="DeviceDetector",l[l.Debug=592702]="Debug",l))(yd||{});var m_=new Zn(!0),Ar=new Zn(!1);var N=m_;var ie={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},p_=new Map([[oe,["Firefox",Dn]],[rs,["Edg",Mn]],[ds,["Chrome",Jn]],[Le,["Safari",Ci]],[Mt,["TBS",Pn]],[ss,["XWEB",wn]],[os&&Xi,["WeChat",xn]],[oo,["QQ(Win)",Un]],[as,["QQ(Mobile)",es]],[ns,["QQ(Mobile X5)",es]],[no,["QQ(Mac)",Vn]],[ao,["QQ(iPad)",Bn]],[lo,["MI",Fn]],[uo,["HW",$n]],[ho,["Samsung",Hn]],[mo,["OPPO",Gn]],[po,["VIVO",Wn]],[is,["EDGE",On]],[ro,["SogouMobile",kn]],[so,["Sogou",Ln]]]);function f_(){let s=p_.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var vd=function(){return!(Qc||is||rs&&Xc<80||oe&&io<56)},bh=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},ia=function(){if(!navigator.mediaDevices)return Di()||R.error(we.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},yh=!1;function Di(){return location.protocol==="http:"&&!Lt?(yh||R.error(P({key:L.NOT_SUPPORTED_HTTP})),yh=!0,!0):!1}var Dd=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Nd=function(){return p(this,null,function*(){if(ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection,r=document.createElement(m.CANVAS);r.getContext("2d");let o=r.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),s=yield t.createOffer(),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),ie.detail.isH264EncodeSupported=i,ie.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},ra=function(){return p(this,null,function*(){if(ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ie.detail.isH264DecodeSupported,isVp8DecodeSupported:ie.detail.isVp8DecodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection;return s=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},sa=yn(()=>p(void 0,null,function*(){if(ie.result&&ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported&&ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return ie;let s=Date.now(),i=vd(),e=Ld(),t=bh(),r=ia(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield Nd(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield ra();if(!o||!n){let l=yield Nd();R.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&he&&Ye&&!ss&&!Mt){let{encode:l,decode:h}=yield g_();o=l,a=h}return ie.result=i&&e&&r&&(o||n)&&(a||c),ie.detail.isBrowserSupported=i,ie.detail.isWebRTCSupported=e,ie.detail.isWebCodecsSupported=t,ie.detail.isMediaDevicesSupported=r,ie.detail.isScreenShareSupported=Ao(),ie.detail.isSmallStreamSupported=Ro(),ie.detail.isH264EncodeSupported=o,ie.detail.isVp8EncodeSupported=n,ie.detail.isH264DecodeSupported=a,ie.detail.isVp8DecodeSupported=c,ie.result||R.error(`${navigator.userAgent} ${An(ie.detail,!1)}`),R_(),N.addNumber({key:523800,value:Date.now()-s}),ie})),__=function(){return ie.result},Ao=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},ta=null;function g_(){return p(this,null,function*(){return ta||(ta=new Promise(s=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),l.close(),h.close(),c.getTracks().forEach(_=>_.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",_=>h.addIceCandidate(_.candidate)),h.addEventListener("icecandidate",_=>l.addIceCandidate(_.candidate)),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield h.setRemoteDescription(u);let f=yield h.createAnswer(),g=bd.default.parse(f.sdp),D=g.media[0].rtp.findIndex(_=>_.codec==="H264");g.media[0].rtp=[g.media[0].rtp[D]],g.media[0].fmtp=g.media[0].fmtp.filter(_=>_.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(_=>_.payload===g.media[0].rtp[0].payload)),f.sdp=bd.default.write(g),yield h.setLocalDescription(f),yield l.setRemoteDescription(f),n=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let[_,C]=yield Promise.all([l.getSenders()[0].getStats(),h.getReceivers()[0].getStats()]);i.encode||_.forEach(M=>{M.type==="outbound-rtp"&&M.mediaType===m.VIDEO&&M.bytesSent>0&&(i.encode=!0)}),i.decode||C.forEach(M=>{M.type==="inbound-rtp"&&M.mediaType===m.VIDEO&&M.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),R.warn("detectH264Supported failed",t),s({encode:!0,decode:!0})}})).then(s=>(s.encode||(s.decode=!0),(!s.encode||!s.decode)&&R.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${Dt}`),s)),ta)})}var T_=(s,i,e)=>{location.protocol==="http:"&&!Lt&&(s[i]=()=>{throw new y({code:S.INVALID_OPERATION,message:we.NOT_SUPPORTED_HTTP})})},Ki=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(ge(s.selected)&&!s.selected):!1};function Nh(){let s="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";s+=`${i} * ${e}`}return s}function vh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Dh(){let s={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){s.isSupported=!0;break}return s.isSupported}function Oh(){return"captureStream"in HTMLCanvasElement.prototype}function Ro(){return os||Se||lt&<<63?!1:!!(vd()&&Oh())}var E_=function(){if(E(window.RTCRtpTransceiver)||!mt()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:ji}),s.addTransceiver(m.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function Rr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Zi(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Zt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function mt(){return ut===11&&!sd?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var ps=!(!mt()||Ye&<<86);function S_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Co="RTCRtpSender"in window;function Od(){return Co&&"replaceTrack"in window.RTCRtpSender.prototype}function yo(){return Co&&"setParameters"in window.RTCRtpSender.prototype&&Zi()}var Md="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,ei=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,kd=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Oi=Co&&"createEncodedStreams"in window.RTCRtpSender.prototype&&cs()>=86,oa="RTCRtpScriptTransform"in window,bo=Co&&(Oi||oa),Ld=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Mh(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return E(window.AudioDecoder)||(s.AudioDecoder=!0),E(window.AudioEncoder)||(s.AudioEncoder=!0),E(window.VideoDecoder)||(s.VideoDecoder=!0),E(window.VideoEncoder)||(s.VideoEncoder=!0),E(window.ImageDecoder)||(s.ImageDecoder=!0),s}function kh(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function Lh(){return!E(window.WebTransport)}function I_(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function A_(){let s={browser:`${qt.name}/${qt.version}`,os:jn(),displayResolution:Nh(),isScreenShareSupported:Ao(),isWebRTCSupported:Ld(),isGetUserMediaSupported:vh(),isWebAudioSupported:Dh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Mh(),isMediaSessionSupported:kh(),isWebTransportSupported:Lh()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var Ph="checkResult";function R_(){us.setItem(Ph,{ua:navigator.userAgent,checkResult:ie})}function Pd(){Di();let s=us.getItem(Ph);s&&s.ua===navigator.userAgent&&(ie=s.checkResult),sa()}function Cr(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var na="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var xh=Be(Qe(),1);var wh=Symbol("instance"),LS=Symbol("abortCtrl"),aa=Symbol("cacheResult"),No=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Oo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},vo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function C_(s){return typeof s=="object"&&s&&"then"in s}var Do=new Map;function pe(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let c=Do.get(t)||[];Do.has(t)||Do.set(t,c),c.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...c){let l=this;if(e.context&&(l=H.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[aa]:Promise.resolve(l[aa]);l.state instanceof No&&l.state.action==e.abortAction&&l.state.abort(l);let h=null;Array.isArray(s)?s.length==0?l.state instanceof No&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(h=new vo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(h=new vo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let u=C=>{if(e.fail&&e.fail.call(this,C),e.sync){if(e.ignoreError)return C;throw C}else return e.ignoreError?Promise.resolve(C):Promise.reject(C)};if(h)return u(h);let f=l.state,g=new No(f,i,n);Oo.call(l,g);let D=C=>{var M;return l[aa]=C,g.aborted||(Oo.call(l,i),(M=e.success)===null||M===void 0||M.call(this,l[aa])),C},_=C=>(Oo.call(l,f,C),u(C));try{let C=a.apply(this,c);return C_(C)?C.then(D).catch(_):e.sync?D(C):Promise.resolve(D(C))}catch(C){return _(new vo(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${C}`,C instanceof Error?C:new Error(String(C))))}}}}var y_=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 Oo(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(H.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var H=class s extends xh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=s.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[wh];r?this.name=r.name+"-"+r.count++:t[wh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Do.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Do.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:h,action:u})=>{typeof l=="string"?r.push({from:l,to:h,action:u}):l.length?l.forEach(f=>{r.push({from:f,to:h,action:u})}):o.push({to:h,action:u})}),r.forEach(({from:l,to:h,action:u})=>{n.add(l),n.add(h),n.add(u+"ing"),t.add(`${l} --> ${u}ing : ${u}`),t.add(`${u}ing --> ${h} : ${u} \u{1F7E2}`),t.add(`${u}ing --> ${l} : ${u} \u{1F534}`)}),o.forEach(({to:l,action:h})=>{t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.forEach(u=>{u!==l&&t.add(`${u} --> ${h}ing : ${h}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=s.instances.get(i),e||s.instances.set(i,e=new s(i,void 0,Object.create(s.prototype)))):(e=s.instances2.get(i),e||s.instances2.set(i,e=new s(i.constructor.name,void 0,Object.create(s.prototype)))),e}static getState(i){var e;return(e=s.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){y_(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Oo.call(this,i)}};H.STATECHANGED="stateChanged";H.UPDATEAFSM="updateAFSM";H.INIT="[*]";H.ON="on";H.OFF="off";H.instances=new Map;H.instances2=new WeakMap;var xd=typeof window!="undefined",Uh=xd&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},b_=xd&&window.cancelIdleCallback||function(s){clearTimeout(s)},Vh=xd&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),ve=class ve{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=v({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=v({delay:1e4,count:0},t):i==="raf"?t=v({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=v({delay:2e3,count:0,backgroundTask:!0},t);let r=w(v({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,ve.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){ve.sharedWorker||(ve.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
11
|
+
`,u+=o)),r&&(u+=`
|
|
12
|
+
Refer to: ${mh("en",a)}
|
|
13
|
+
`),u}var Cd=Ue(Ih(),1);var s_=1,o_=0,Kn=class{constructor(i=!0){c(this,"countMap",new Map);c(this,"distributionMap",new Map);c(this,"version");c(this,"log",C.createLogger({id:"kv"}));i&&(E.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===p.AUDIO?501700:511700,cost:t})}),E.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===p.AUDIO?501700:511700,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Cn(this.version||ve),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(([r,o])=>({uint32_item_key:r,uint32_item_value:o}))}))};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 o;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 r=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(Q(t))n=Math.floor(e/t);else for(let d=t.length-1;d>0;d--)if(e>t[d]){n=d;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:s_,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(Q(e)?t=e:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:o_,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},Zn=(z=>(z[z.enterRoom=500700]="enterRoom",z[z.exitRoom=500701]="exitRoom",z[z.switchRole=500702]="switchRole",z[z.destroy=500703]="destroy",z[z.startLocalAudio=500704]="startLocalAudio",z[z.updateLocalAudio=500705]="updateLocalAudio",z[z.stopLocalAudio=500706]="stopLocalAudio",z[z.startLocalVideo=500707]="startLocalVideo",z[z.updateLocalVideo=500708]="updateLocalVideo",z[z.stopLocalVideo=500709]="stopLocalVideo",z[z.startScreenShare=500710]="startScreenShare",z[z.updateScreenShare=500711]="updateScreenShare",z[z.stopScreenShare=500712]="stopScreenShare",z[z.startRemoteVideo=500713]="startRemoteVideo",z[z.updateRemoteVideo=500714]="updateRemoteVideo",z[z.stopRemoteVideo=500715]="stopRemoteVideo",z[z.muteRemoteAudio=500716]="muteRemoteAudio",z[z.setRemoteAudioVolume=500717]="setRemoteAudioVolume",z[z.use=500718]="use",z[z.sendSEIMessage=5e5]="sendSEIMessage",z[z.sendCustomMessage=500001]="sendCustomMessage",z))(Zn||{}),Sd=(l=>(l[l.AudioMixer=550700]="AudioMixer",l[l.AIDenoiser=551700]="AIDenoiser",l[l.VirtualBackground=570700]="VirtualBackground",l[l.Beauty=571700]="Beauty",l[l.Watermark=572700]="Watermark",l[l.BasicBeauty=574700]="BasicBeauty",l[l.CDNStreaming=590700]="CDNStreaming",l[l.DeviceDetector=591700]="DeviceDetector",l[l.Debug=592700]="Debug",l))(Sd||{}),Id=(l=>(l[l.AudioMixer=550701]="AudioMixer",l[l.AIDenoiser=551701]="AIDenoiser",l[l.VirtualBackground=570701]="VirtualBackground",l[l.Beauty=571701]="Beauty",l[l.Watermark=572701]="Watermark",l[l.BasicBeauty=574701]="BasicBeauty",l[l.CDNStreaming=590701]="CDNStreaming",l[l.DeviceDetector=591701]="DeviceDetector",l[l.Debug=592701]="Debug",l))(Id||{}),Ad=(l=>(l[l.AudioMixer=550702]="AudioMixer",l[l.AIDenoiser=551702]="AIDenoiser",l[l.VirtualBackground=570702]="VirtualBackground",l[l.Beauty=571702]="Beauty",l[l.Watermark=572702]="Watermark",l[l.BasicBeauty=574702]="BasicBeauty",l[l.CDNStreaming=590702]="CDNStreaming",l[l.DeviceDetector=591702]="DeviceDetector",l[l.Debug=592702]="Debug",l))(Ad||{});var n_=new Kn(!0),Sr=new Kn(!1);var N=n_;var ie={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},a_=new Map([[se,["Firefox",vn]],[ts,["Edg",On]],[as,["Chrome",Wn]],[Oe,["Safari",Si]],[vt,["TBS",Ln]],[is,["XWEB",Pn]],[rs&&Ji,["WeChat",wn]],[ro,["QQ(Win)",xn]],[os,["QQ(Mobile)",Kr]],[ss,["QQ(Mobile X5)",Kr]],[so,["QQ(Mac)",Un]],[oo,["QQ(iPad)",Vn]],[ao,["MI",Bn]],[co,["HW",Fn]],[lo,["Samsung",$n]],[uo,["OPPO",Hn]],[ho,["VIVO",Gn]],[es,["EDGE",Dn]],[to,["SogouMobile",kn]],[io,["Sogou",Mn]]]);function c_(){let s=a_.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var yd=function(){return!(qc||es||ts&&Jc<80||se&&eo<56)},Ch=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},ta=function(){if(!navigator.mediaDevices)return bi()||C.error(Me.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},Ah=!1;function bi(){return location.protocol==="http:"&&!Ot?(Ah||C.error(U({key:x.NOT_SUPPORTED_HTTP})),Ah=!0,!0):!1}var bd=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Rd=function(){return f(this,null,function*(){if(ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection,r=document.createElement(p.CANVAS);r.getContext("2d");let o=r.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),s=yield t.createOffer(),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),ie.detail.isH264EncodeSupported=i,ie.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},ia=function(){return f(this,null,function*(){if(ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ie.detail.isH264DecodeSupported,isVp8DecodeSupported:ie.detail.isVp8DecodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection;return s=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},ra=Rn(()=>f(void 0,null,function*(){if(ie.result&&ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported&&ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return ie;let s=Date.now(),i=yd(),e=Od(),t=Ch(),r=ta(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield Rd(),{isH264DecodeSupported:a,isVp8DecodeSupported:d}=yield ia();if(!o||!n){let l=yield Rd();C.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&ue&&Xe&&!is&&!vt){let{encode:l,decode:u}=yield l_();o=l,a=u}return ie.result=i&&e&&r&&(o||n)&&(a||d),ie.detail.isBrowserSupported=i,ie.detail.isWebRTCSupported=e,ie.detail.isWebCodecsSupported=t,ie.detail.isMediaDevicesSupported=r,ie.detail.isScreenShareSupported=So(),ie.detail.isSmallStreamSupported=Io(),ie.detail.isH264EncodeSupported=o,ie.detail.isVp8EncodeSupported=n,ie.detail.isH264DecodeSupported=a,ie.detail.isVp8DecodeSupported=d,ie.result||C.error(`${navigator.userAgent} ${In(ie.detail,!1)}`),__(),N.addNumber({key:523800,value:Date.now()-s}),ie})),d_=function(){return ie.result},So=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},ea=null;function l_(){return f(this,null,function*(){return ea||(ea=new Promise(s=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),l.close(),u.close(),d.getTracks().forEach(R=>R.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let d=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",R=>u.addIceCandidate(R.candidate)),u.addEventListener("icecandidate",R=>l.addIceCandidate(R.candidate)),l.addTrack(d.getVideoTracks()[0],d);let h=yield l.createOffer();yield l.setLocalDescription(h),yield u.setRemoteDescription(h);let m=yield u.createAnswer(),_=Cd.default.parse(m.sdp),I=_.media[0].rtp.findIndex(R=>R.codec==="H264");_.media[0].rtp=[_.media[0].rtp[I]],_.media[0].fmtp=_.media[0].fmtp.filter(R=>R.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(R=>R.payload===_.media[0].rtp[0].payload)),m.sdp=Cd.default.write(_),yield u.setLocalDescription(m),yield l.setRemoteDescription(m),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let[R,D]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||R.forEach(W=>{W.type==="outbound-rtp"&&W.mediaType===p.VIDEO&&W.bytesSent>0&&(i.encode=!0)}),i.decode||D.forEach(W=>{W.type==="inbound-rtp"&&W.mediaType===p.VIDEO&&W.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),C.warn("detectH264Supported failed",t),s({encode:!0,decode:!0})}})).then(s=>(s.encode||(s.decode=!0),(!s.encode||!s.decode)&&C.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${bt}`),s)),ea)})}var u_=(s,i,e)=>{location.protocol==="http:"&&!Ot&&(s[i]=()=>{throw new b({code:S.INVALID_OPERATION,message:Me.NOT_SUPPORTED_HTTP})})},zi=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(fe(s.selected)&&!s.selected):!1};function Rh(){let s="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";s+=`${i} * ${e}`}return s}function yh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function bh(){let s={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){s.isSupported=!0;break}return s.isSupported}function Nh(){return"captureStream"in HTMLCanvasElement.prototype}function Io(){return rs||ge||ct&&ct<63?!1:!!(yd()&&Nh())}var h_=function(){if(g(window.RTCRtpTransceiver)||!ut()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:Gi}),s.addTransceiver(p.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function Ir(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Qi(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function zt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ut(){return dt===11&&!td?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var hs=!(!ut()||Xe&&ct<86);function m_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Ao="RTCRtpSender"in window;function Nd(){return Ao&&"replaceTrack"in window.RTCRtpSender.prototype}function Co(){return Ao&&"setParameters"in window.RTCRtpSender.prototype&&Qi()}var vd="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Qt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Dd=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ni=Ao&&"createEncodedStreams"in window.RTCRtpSender.prototype&&ns()>=86,sa="RTCRtpScriptTransform"in window,Ro=Ao&&(Ni||sa),Od=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function vh(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(s.AudioDecoder=!0),g(window.AudioEncoder)||(s.AudioEncoder=!0),g(window.VideoDecoder)||(s.VideoDecoder=!0),g(window.VideoEncoder)||(s.VideoEncoder=!0),g(window.ImageDecoder)||(s.ImageDecoder=!0),s}function Dh(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function Oh(){return!g(window.WebTransport)}function p_(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function f_(){let s={browser:`${Jt.name}/${Jt.version}`,os:Jn(),displayResolution:Rh(),isScreenShareSupported:So(),isWebRTCSupported:Od(),isGetUserMediaSupported:yh(),isWebAudioSupported:bh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:vh(),isMediaSessionSupported:Dh(),isWebTransportSupported:Oh()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var kh="checkResult";function __(){ds.setItem(kh,{ua:navigator.userAgent,checkResult:ie})}function kd(){bi();let s=ds.getItem(kh);s&&s.ua===navigator.userAgent&&(ie=s.checkResult),ra()}function Ar(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var oa="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Lh=Ue(qe(),1);var Mh=Symbol("instance"),yS=Symbol("abortCtrl"),na=Symbol("cacheResult"),yo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,vo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},bo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function g_(s){return typeof s=="object"&&s&&"then"in s}var No=new Map;function me(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let d=No.get(t)||[];No.has(t)||No.set(t,d),d.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...d){let l=this;if(e.context&&(l=B.get(typeof e.context=="function"?e.context.call(this,...d):e.context)),l.state===i)return e.sync?l[na]:Promise.resolve(l[na]);l.state instanceof yo&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(s)?s.length==0?l.state instanceof yo&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(u=new bo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(u=new bo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let h=D=>{if(e.fail&&e.fail.call(this,D),e.sync){if(e.ignoreError)return D;throw D}else return e.ignoreError?Promise.resolve(D):Promise.reject(D)};if(u)return h(u);let m=l.state,_=new yo(m,i,n);vo.call(l,_);let I=D=>{var W;return l[na]=D,_.aborted||(vo.call(l,i),(W=e.success)===null||W===void 0||W.call(this,l[na])),D},R=D=>(vo.call(l,m,D),h(D));try{let D=a.apply(this,d);return g_(D)?D.then(I).catch(R):e.sync?I(D):Promise.resolve(I(D))}catch(D){return R(new bo(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${D}`,D instanceof Error?D:new Error(String(D))))}}}}var T_=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 vo(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(B.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var B=class s extends Lh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=s.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Mh];r?this.name=r.name+"-"+r.count++:t[Mh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=No.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);No.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:h})=>{typeof l=="string"?r.push({from:l,to:u,action:h}):l.length?l.forEach(m=>{r.push({from:m,to:u,action:h})}):o.push({to:u,action:h})}),r.forEach(({from:l,to:u,action:h})=>{n.add(l),n.add(u),n.add(h+"ing"),t.add(`${l} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${u} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${l} : ${h} \u{1F534}`)}),o.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(h=>{h!==l&&t.add(`${h} --> ${u}ing : ${u}`)})});let d=[...t];return Object.defineProperties(i,{stateDiagram:{value:d},allStates:{value:n}}),d}static get(i){let e;return typeof i=="string"?(e=s.instances.get(i),e||s.instances.set(i,e=new s(i,void 0,Object.create(s.prototype)))):(e=s.instances2.get(i),e||s.instances2.set(i,e=new s(i.constructor.name,void 0,Object.create(s.prototype)))),e}static getState(i){var e;return(e=s.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){T_(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){vo.call(this,i)}};B.STATECHANGED="stateChanged";B.UPDATEAFSM="updateAFSM";B.INIT="[*]";B.ON="on";B.OFF="off";B.instances=new Map;B.instances2=new WeakMap;var Ld=typeof window!="undefined",Ph=Ld&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},E_=Ld&&window.cancelIdleCallback||function(s){clearTimeout(s)},wh=Ld&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),be=class be{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=v({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=v({delay:1e4,count:0},t):i==="raf"?t=v({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=v({delay:2e3,count:0,backgroundTask:!0},t);let r=M(v({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,be.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){be.sharedWorker||(be.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
14
14
|
const timers = new Map();
|
|
15
15
|
self.onmessage = function(e) {
|
|
16
16
|
const { taskId, delay, type } = e.data;
|
|
@@ -23,14 +23,14 @@ Refer to: ${_h("en",a)}
|
|
|
23
23
|
timers.delete(taskId);
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
|
-
`],{type:"application/javascript"}))),
|
|
27
|
-
${t.stack}`)),this.sendRequest(Ei(this._configs.sdkAppId,Gi.LOG),r)}sendRequest(i,e){setTimeout(()=>Ai({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},te=new Ud;var ri=new WeakMap;function ot({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=jt({retryFunction:n.value,settings:s,onError({error:c,retry:l,reject:h,retryFuncArgs:u}){var f;i?i.call(this,c,()=>{var g;(g=ri.get(r))!=null&&g.has(o)?l():h(c)},h,u):(f=ri.get(r))!=null&&f.has(o)?l():h(c)},onRetrying(c,l){var h;Jt(e)&&e.call(this,c,l),(h=ri.get(r))!=null&&h.has(o)&&(ri.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=ri.get(r);return l?l.set(o,{args:c}):ri.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var h;return(h=ri.get(r))==null?void 0:h.delete(o)})},n}}function ko({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,l;if((c=ri.get(t))!=null&&c.has(s)){let{stopRetry:h,args:u}=ri.get(t).get(s),f=!0;if(e){for(let g of u)if(!a.find(D=>D===g)){f=!1;break}}f&&(i&&i.apply(this,a),h&&h(),(l=ri.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var si=class extends H{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=zs,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}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._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=P({key:L.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new y({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!zi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(m.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():id?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 Ge(this.element,this.element).add(m.PLAYING,e).add(m.ENDED,e).add(m.PAUSE,e).add(m.ERROR,e).add(m.LOADEDDATA,e).add(m.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);ii==null||ii.create(e,e).add(m.ENDED,t).add(m.MUTE,t).add(m.UNMUTE,t),e.readyState===m.ENDED&&this.handleTrackEvent({type:m.ENDED}),e.muted&&this.handleTrackEvent({type:m.MUTE})}}bindAutoPlayEvent(){T.on(I.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&be(e)}unbindEvents(){this.element&&be(this.element),this.unbindTrackEvents(),T.off(I.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case m.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(m.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case m.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(m.ENDED);break;case m.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(m.PAUSE),Se&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case m.ERROR:if(this.element&&this.element.error){this.handlePaused(m.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),te.uploadEvent({log:`stat-${this.kind}-${rt.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),Kc||Yc?this.emit(le.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case m.LOADEDDATA:this.kind===m.VIDEO&&this.emit(le.LOADED_DATA);break;case m.LOADEDMETADATA:this.kind===m.VIDEO&&this.emit(le.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),te.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),N.addSuccessEvent({key:this.kind===m.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),te.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),N.addFailedEvent({key:this.kind===m.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(le.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ii(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ii(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case m.ENDED:this.handleStopped(m.ENDED);break;case m.MUTE:this.handlePaused(m.MUTE);break;case m.UNMUTE:this._isElementPlayingFired?this.handlePlaying(m.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(le.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(le.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(le.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};b([ot({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],si.prototype,"doReplayByRecreateMediaStream",1),b([pe([],"PLAYING",{sync:!0})],si.prototype,"handlePlaying",1),b([pe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],si.prototype,"handlePaused",1),b([pe([],"STOPPED",{sync:!0})],si.prototype,"handleStopped",1);var Mi="trtc_autoplay",Vd=`${Mi}_mask`,fs=`${Mi}_wrapper`,Bh=`${Mi}_header`,Bd=`${Mi}_content`,ca=`${Mi}_action_wrapper`,Fd=`${Mi}_question`,$d=`${Mi}_collapse`,da=`${Mi}_action_confirm`,Fh=`${Mi}_detail`,$h="#2473E8",Gd="dialog",v_=`${Gd}-show`,D_=`${Gd}-1`,O_=`${Gd}-2`,Hh=!1,Wd=()=>!!document.querySelector(`.${fs}`),Wh=`${Ht}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Gh=`<br><a href='${Wh}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,M_=`${Nt()?`\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${Gh}`:`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. ${Gh}`}`,Hd=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Nt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Hh){let i=document.createElement("style");i.innerHTML=`.${Vd}{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;}.${Vd} div:not(.${ca}){display:block !important;}.${fs}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${fs} a{color:${$h};}.${Bh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Bd}{margin:8px 0;}.${ca}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${$d}{margin-right:auto;cursor:pointer}.${Fd}{height:100%;line-height:16px;cursor:pointer;}.${da}{margin-left:8px;color:#fff;background:${$h};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${da}:hover{opacity:0.9;}.${$d},.${da},.${Bd},.${Fd}{font-size:14px;}@media screen and (max-width:750px){.${fs}{width:80vw;}}`,document.head.appendChild(i),Hh=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Vd}"><div class='${fs}'><div class='${Bh}'>${location.host}</div><div class='${Bd}'>${this.content}</div><div class='${Fh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${M_}</div><div class='${ca}'></div></div></div>`.trim();let e=document.createElement("button");e.className=da,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Fd,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
|
+
`],{type:"application/javascript"}))),be.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=be.workerTasks.get(e.data.taskId);r&&(be.isBreakLoop(r)?((t=be.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),be.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),be.workerTasks.set(i.taskID,i),be.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!be.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=L(),t,r=()=>{if(t=L()-e,t>=i.delay&&(e=L()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!be.isBreakLoop(i))return i.ricID=Ph(r,{timeout:i.delay})};return i.ricID=Ph(r,{timeout:i.delay})}static raf(i){let e=L(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=L()-e,e=L(),i.callback(),i.loopCount+=1,be.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=L()-e,t>=i.delay&&(e=L()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!be.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=L()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&wh&&wh(r),o&&E_(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};c(be,"taskMap",new Map),c(be,"currentTaskID",1),c(be,"sharedWorker",null),c(be,"workerTasks",new Map);var Md=be,re=Md;var wS={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:p.SEI_MESSAGE,ERROR:"error"};var de={LOADED_DATA:p.LOADEDDATA,LOADED_META_DATA:p.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Kt={};ui(Kt,{create:()=>Fe,remove:()=>Ce});var Do=new WeakMap;function Fe(s,i){Do.has(s)||Do.set(s,[]);let e=Do.get(s),r={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),r)};return r}function Ce(s){let i=Do.get(s);i&&(i.forEach(e=>e()),Do.delete(s))}var Pd=class{constructor(){c(this,"_roomIdMap",new Map);c(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:ve,env:hi.QCLOUD,browserVersion:Jt.name+Jt.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){Ot||!C.isAbleToUpload||this._configs.env===hi.QCLOUD&&this.uploadEventToKibana(M(v({},i),{result:"success"}))}logFailedEvent(i){if(Ot||!C.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||S.UNKNOWN};this._configs.env===hi.QCLOUD&&this.uploadEventToKibana(M(v({},n),{error:r}))}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 r={timestamp:cn(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:ve,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
27
|
+
${t.stack}`)),this.sendRequest(fi(this._configs.sdkAppId,Fi.LOG),r)}sendRequest(i,e){setTimeout(()=>Ti({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},ee=new Pd;var Zt=new WeakMap;function rt({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Wt({retryFunction:n.value,settings:s,onError({error:d,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,d,()=>{var _;(_=Zt.get(r))!=null&&_.has(o)?l():u(d)},u,h):(m=Zt.get(r))!=null&&m.has(o)?l():u(d)},onRetrying(d,l){var u;Gt(e)&&e.call(this,d,l),(u=Zt.get(r))!=null&&u.has(o)&&(Zt.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...d){let l=Zt.get(r);return l?l.set(o,{args:d}):Zt.set(r,new Map([[o,{args:d}]])),a.apply(this,d).finally(()=>{var u;return(u=Zt.get(r))==null?void 0:u.delete(o)})},n}}function Oo({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var d,l;if((d=Zt.get(t))!=null&&d.has(s)){let{stopRetry:u,args:h}=Zt.get(t).get(s),m=!0;if(e){for(let _ of h)if(!a.find(I=>I===_)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=Zt.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var ei=class extends B{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;c(this,"id");c(this,"element",null);c(this,"track");c(this,"url");c(this,"attr");c(this,"mode");c(this,"muted");c(this,"_log");c(this,"_pausedRetryCount");c(this,"_isElementPlayingFired",!1);c(this,"_interval");c(this,"_delayDestroyTimeoutId",0);c(this,"_playSuccessResolve");c(this,"_isReplayByRecreateMediaStreamCalled",!1);c(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=cr,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}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 f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=U({key:x.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new b({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!ji?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Zc?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 Fe(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Kt==null||Kt.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){E.on(T.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Ce(e)}unbindEvents(){this.element&&Ce(this.element),this.unbindTrackEvents(),E.off(T.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE),ge&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),ee.uploadEvent({log:`stat-${this.kind}-${et.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),zc||Xc?this.emit(de.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(de.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(de.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ee.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),N.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),ee.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),N.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(de.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{gi(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),gi(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this._isElementPlayingFired?this.handlePlaying(p.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([rt({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],ei.prototype,"doReplayByRecreateMediaStream",1),y([me([],"PLAYING",{sync:!0})],ei.prototype,"handlePlaying",1),y([me("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],ei.prototype,"handlePaused",1),y([me([],"STOPPED",{sync:!0})],ei.prototype,"handleStopped",1);var vi="trtc_autoplay",wd=`${vi}_mask`,ms=`${vi}_wrapper`,xh=`${vi}_header`,xd=`${vi}_content`,aa=`${vi}_action_wrapper`,Ud=`${vi}_question`,Vd=`${vi}_collapse`,ca=`${vi}_action_confirm`,Uh=`${vi}_detail`,Vh="#2473E8",Fd="dialog",I_=`${Fd}-show`,A_=`${Fd}-1`,C_=`${Fd}-2`,Bh=!1,$d=()=>!!document.querySelector(`.${ms}`),$h=`${Bt}/${Rt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Fh=`<br><a href='${$h}' target='_blank'>${Rt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,R_=`${Rt()?`\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${Fh}`:`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. ${Fh}`}`,Bd=class{constructor(){c(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");c(this,"_dialogNode",null);c(this,"_bodyPosition","");c(this,"_showDetail",!1);c(this,"_isCollapseClicked",!1);c(this,"_isQuestionClicked",!1);if(Rt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Bh){let i=document.createElement("style");i.innerHTML=`.${wd}{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;}.${wd} div:not(.${aa}){display:block !important;}.${ms}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${ms} a{color:${Vh};}.${xh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${xd}{margin:8px 0;}.${aa}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Vd}{margin-right:auto;cursor:pointer}.${Ud}{height:100%;line-height:16px;cursor:pointer;}.${ca}{margin-left:8px;color:#fff;background:${Vh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${ca}:hover{opacity:0.9;}.${Vd},.${ca},.${xd},.${Ud}{font-size:14px;}@media screen and (max-width:750px){.${ms}{width:80vw;}}`,document.head.appendChild(i),Bh=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${wd}"><div class='${ms}'><div class='${xh}'>${location.host}</div><div class='${xd}'>${this.content}</div><div class='${Uh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${R_}</div><div class='${aa}'></div></div></div>`.trim();let e=document.createElement("button");e.className=ca,e.innerText=Rt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Ud,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
28
|
<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">
|
|
29
29
|
<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"/>
|
|
30
30
|
<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"/>
|
|
31
31
|
<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"/>
|
|
32
32
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=$d,r.innerText=`${Nt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${ca}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){Wd()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${fs}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),te.uploadEvent({log:v_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){R.warn("confirm clicked, try resume stream"),T.emit(I.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Fh}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||te.uploadEvent({log:D_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Wh,"_blank"),this._isQuestionClicked||te.uploadEvent({log:O_}),this._isQuestionClicked=!0}},Jh=Hd;var pt=class extends si{constructor(e){super(e,m.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(m.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var 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(m.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(m.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===m.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,o;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===m.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this.container&&this.container===document.getElementById(this.container.id)||(this._pausedRetryCount=zs,this._log.info(`element ${(o=this.container)==null?void 0:o.id} is recreated`)),this._pausedRetryCount>0&&!Wd()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===m.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===m.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((o=this.element)==null||o.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}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}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(le.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Cr()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function yr(s,i){return p(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Lo;typeof AudioContext!="undefined"?Lo=AudioContext:typeof webkitAudioContext!="undefined"?Lo=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Lo=mozAudioContext);var xt,jh=-1;qh();function qh(){try{if(xt)return;xt=new Lo({sampleRate:48e3}),xt.onstatechange=()=>{R.info(`context state: ${xt.state}${xt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),_s()},clearTimeout(jh)}catch(s){R.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof Lo}`),jh=setTimeout(qh,1e3)}}var _s=()=>{xt.state==="suspended"?(gs(),document.addEventListener("click",_s)):xt.state==="interrupted"?gs():(document.removeEventListener("visibilitychange",_s),document.removeEventListener("click",_s))},Jd=0,jd=-1;function gs(){return new Promise((s,i)=>{if(xt.state==="running")return s();Date.now()-Jd<1e3?(clearTimeout(jd),jd=setTimeout(()=>{Jd=Date.now(),xt.resume().then(s,i)},1e3)):(clearTimeout(jd),Jd=Date.now(),xt.resume().then(s,i))}).catch(s=>{R.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",_s)})}document.addEventListener("click",_s);var Re=s=>xt;var We=class{constructor(){d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),N.addSuccessEvent({key:502701})}catch(r){R.error(r),N.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),N.addSuccessEvent({key:502702})}catch(e){R.error(e),N.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.node2||this.node).connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||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}},la=class extends We{constructor(e=256){super();this.fftSize=e;d(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,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Po=class{constructor(){d(this,"source",new We);d(this,"gain",new We);d(this,"destination",new We)}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(Re().createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.replaceNode(qd(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}},Ts=class extends Po{constructor(e){super();this.context=e;d(this,"denoiser",new We);d(this,"voiceChanger",new We);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.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.voiceChanger.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.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.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}},ua=class{constructor(){d(this,"audioContext",Re("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(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]}},Xh=new WeakMap;function qd(s){let i=Xh.get(s);if(i)return i;let e=Re();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return Xh.set(s,i),i}var ft=class ft{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(I.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-ft.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!ft.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';ft.workletReady=yr(ft.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return ft.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ft.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{ft.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),te.logFailedEvent({userId:this._log.userId,eventType:rt.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Re("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{ft.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];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(I.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(ft,"lastMessageTime",0),d(ft,"audioContext",Re("volume-meter")),d(ft,"workletReady");var ha=ft,ma=class extends We{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new ha(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}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()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},br=ha;var Kh=Be(Qe(),1);var Qh=s=>i=>i.deviceId===s;var wo=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Es(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Qh(r.deviceId))){let o=`${this.kind}${this.type}Added`;R.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Qh(r.deviceId))){let o=`${this.kind}${this.type}Removed`;R.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Xd=class extends Kh.EventEmitter{constructor(){super();d(this,"audioInputs",new wo(m.AUDIO));d(this,"videoInputs",new wo(m.VIDEO));d(this,"audioOutputs",new wo(m.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run("interval",()=>{this.update()},{delay:1e4}))}init(){pa().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 pa(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ke=Ws||Wr?null:new Xd;function Es(s){return s.deviceId===s.groupId&&s.groupId===""}function pa(){return p(this,arguments,function*(s=0){if(Di()||!ia())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Es(t)&&(t.kind===m.AUDIO_INPUT?e.audio=!0:t.kind===m.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&gs()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&zd.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function nt(s=!1){return ke.update(s?1:0).then(i=>i.audioInputs.devices)}function _t(s=!1){return ke.update(s?2:0).then(i=>i.videoInputs.devices)}var Yh=!1;function Zh(){return p(this,null,function*(){try{Yh||(Yh=!0,R.info(`speakers:${(yield er()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function er(s=!1){return p(this,null,function*(){return(Se||Le)&&(s=!1),ke.update(s?1:0).then(i=>i.audioOutputs.devices)})}var zd=new Set;function em(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${m.VIDEO_INPUT}`;return!!zd.has(t)}function tm(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${m.AUDIO_INPUT}`;return!!zd.has(t)}function Qd(s,i){return p(this,null,function*(){let t=(yield nt()).find(r=>r.deviceId===ur);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function im(o){return p(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===m.AUDIO&&s===ur?yield Qd(e,t):!0})}var fa,Yd=class extends Po{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeDestination");d(this,"analyser",new la);this.volumeMeter=new ma({log:this.log}),this.volumeDestination=new We,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},_a=class s extends si{constructor(e){super(e,m.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Re("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Yd(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Xt==="15.2"||Xt==="15.3"||Xt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=fa||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===fa&&(fa=void 0),this.bindElementEvents()}play(e){return p(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Re("player").createAnalyser()),Zh(),Fe(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.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()}},ga=class extends _a{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(le.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Ta=class extends _a{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new We);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(Re("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(le.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):Se||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),be(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&zi&&(fa=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Nr=class extends H{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?Ta:pt}){var a;super();d(this,"id",go());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof ki?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof ki}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(le.PLAYER_STATE_CHANGED,c=>{T.emit(I.PLAYER_STATE_CHANGED,v({track:this},c)),this.emit("player-state-changed",c)}),this.kind===m.VIDEO&&(this.player.on(le.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(le.LOADED_DATA),T.emit(I.VIDEO_LOADED_DATA,{track:this})}),this.player.on(le.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(le.LOADED_META_DATA)}),this.player.on(le.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(h=>h.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(le.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?m.AUDIO:m.VIDEO}get strMediaType(){return this.mediaType===4?m.VIDEO:this.mediaType===2?m.SCREEN:m.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return p(this,null,function*(){let r=_e(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 pt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),_e(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===m.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),t&&!E(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof pt&&this.player.setContainer(r)),T.emit(I.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(t),_e(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==m.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(ge(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===m.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new pt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Wc(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.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(!0)}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?I.TRACK_MUTED:I.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Ge(e,e).add(m.MUTE,this.onTrackMuted).add(m.UNMUTE,this.onTrackUnmuted).add(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){be(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Wc(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new Jh;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof pt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===le.LOADED_META_DATA&&!r&&!o||(e===le.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:r,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};b([pe([],H.INIT,{sync:!0})],Nr.prototype,"close",1);var k_=Object.prototype.hasOwnProperty,{toString:dR}=Object.prototype;function L_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(He(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(k_.call(s,i))return!1;return!0}}return!1}var oi=L_;var P_=function(s){return p(this,null,function*(){let i=x_(s);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield nt(),R.info(`microphones: ${Tt(e.map(o=>w(v({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield _t(),R.info(`cameras: ${Tt(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return kd&&o.getTracks().forEach(n=>{R.info(`${n.kind} capabilities: ${Tt(n.getCapabilities(),{keysToInclude:Sn})}`)}),i.audio&&gs(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=P({key:L.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=P({key:L.MICROPHONE_NOT_FOUND}))),new y({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},w_=jt({retryFunction:P_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!Le||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&rm(t[0].microphoneId,!1),t[0].cameraId&&rm(t[0].cameraId,!0)},onRetrying:s=>{R.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{te.logFailedEvent({eventType:rt.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{te.logSuccessEvent({eventType:rt.GET_USER_MEDIA_RETRY}),te.uploadEvent({log:`stat-${rt.GET_USER_MEDIA_RETRY}-success-${s}`})}});function rm(s,i){return p(this,null,function*(){let t=(i?yield _t():yield nt()).find(r=>r.deviceId===s);t&&se(t.getCapabilities)&&R.warn(Tt(t.getCapabilities(),{keysToInclude:Sn}))})}function x_(s){return{audio:U_(s),video:V_(s)}}function U_(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!oi(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(Q(s.channelCount)&&(i.channelCount=s.channelCount),ge(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),ge(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),ge(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),oi(i)?!0:i)}function V_(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!oi(e)?e:(s.width&&(e.width={ideal:s.width},i&&!oe&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!oe&&(e.height.max=s.height)),oe&&kt&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),oi(e)?!0:e)}var sm=w_;function Ea(s){return z((i,e)=>function(...t){return p(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Ze(s){return z((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function Sa(s){return z((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function z(s){return function(i,e,t){return t.value=s(t.value,e),t}}var om=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var B_=0,Ia=class{constructor(){d(this,"log",R.createLogger({id:`fq${++B_}`}));d(this,"isRunning",!1);d(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 o,n;let t=v({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}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:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},xo=new WeakMap,Aa=new WeakMap;function ni(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=xo.get(this)||new Ia;return xo.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function nm(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=xo.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let h=!0;return c.args.forEach(u=>{o.find(f=>f===u)||(h=!1)}),h?(c.reject(new y({code:S.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function Ra(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,l;let n=[];return(c=(a=xo.get(this))==null?void 0:a.queue)==null||c.forEach(h=>n.push(h)),(l=Aa.get(this))==null||l.forEach(h=>h==null?void 0:h.queue.forEach(u=>n.push(u))),n.forEach(h=>{h.reject(new y({code:S.API_CALL_ABORTED,message:s}))}),xo.delete(this),Aa.delete(this),r.apply(this,o)},t}}function Li(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Aa.get(this)||new Map,c=a.get(o(n))||new Ia;return a.set(o(n),c),Aa.set(this,a),c.push({fn:r,args:n,context:this})},t}}function at(s,i){return z((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=x();return qi(n)?n.then(c=>(i?N.addSuccessEvent({key:o,cost:x()-a}):N.addSuccessEvent({key:o}),c)).catch(c=>{throw N.addFailedEvent({key:o,error:c}),c}):(N.addSuccessEvent({key:o}),n)}catch(n){throw N.addFailedEvent({key:o,error:n}),n}})}var vr=class vr extends Nr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Ge(e,e).add(m.MUTE,this.onTrackMuted).add(m.UNMUTE,this.onTrackUnmuted).add(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){be(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){var t;try{let r=x();T.emit(I.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield sm(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(I.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-r}),o}catch(r){throw T.emit(I.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===H.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(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(I.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&ei){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield im({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),pa().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===m.AUDIO&&!tm(this.mediaTrack)||this.kind===m.VIDEO&&!em(this.mediaTrack)||this._isRecapturing||e&&kt&&Le)}onTrackMuted(){if(super.onTrackMuted(),om(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<qr){setTimeout(()=>this.onTrackMuted(),qr);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Se||he)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Fe(vr.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<qr){setTimeout(()=>this.onTrackEnded(),qr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield nt():yield _t()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),T.emit(I.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),T.emit(I.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof Je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Uo.get(t)||0)+1;if(Uo.set(t,r),r>=3){let o=e?(yield _t()).find(n=>!Uo.has(n.deviceId)):(yield nt()).find(n=>!Uo.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.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([pe(H.INIT,"capture",{ignoreError:!0,sync:!0})],vr.prototype,"setStateToCapture",1),b([ni()],vr.prototype,"capture",1),b([pe("capture","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),T.emit(I.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let c=this.kind===m.AUDIO,l=this.stat.bytesSent>0;N[l?"addSuccessEvent":"addFailedEvent"]({key:c?503700:513702}),l||(N.addEnum({key:c?503701:513703,value:_o()}),te.uploadEvent({log:`stat-encode-failed-${this.kind}-${Tr()||bi()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===S.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),at(521714,!1)],vr.prototype,"publish",1),b([z(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),pe([],"capture",{sync:!0})],vr.prototype,"unpublish",1);var ki=vr,Uo=new Map;T.on(I.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&Uo.delete(s.track.deviceId)});var St=class s extends ki{constructor(e){super(1,ga);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new We);d(this,"_output",new We);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Ts(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return br.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return p(this,null,function*(){let t=this.trackSettings||{};N.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),N.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),N.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield Fe(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===ur){if(yield Qd(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),T.emit(I.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(){ke&&!ke.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ke.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)}`),Te(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield nt();t[0]?this.recapture(t[0].deviceId):ke.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!E(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(oe||Le?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&N.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Se&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Re().createGain()),this._output.setNode(Re().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}addDenoiser(e){var t;if(lt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}N.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),ke.off("audioInputAdded",this.handleMicrophoneAdded,this),ke.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Fe(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield nt()).find(o=>o.deviceId!==e);if(r)yield Fe(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Pi=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=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var Ca=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Pi(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((f,g)=>f+g.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),h=new DataView(i.data),u=0;for(let f=0;f<n.length;f++)for(let g=0;g<n[f].dataView.byteLength;g++)l.setInt8(u++,n[f].dataView.getInt8(g));for(let f=0;f<i.data.byteLength;f++)l.setInt8(u++,h.getInt8(f));return i.data=c,n.length}return 0}};var Dr=class Dr extends ki{constructor(e,t=4){super(t,pt);d(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Ca);this.manager=e;let r=()=>{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(w(v({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!ei||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return p(this,null,function*(){var t,r,o;if(K(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Fe(Dr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),Fe(Dr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){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:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=v({},e),r=t.width>t.height;t.width*t.height<=160*120&&he&&Ye&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&rd&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(Ye||oe)&&!od()&&t.width*t.height<=640*360&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),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(w(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,o=this.settings;if(!(!(o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate)||!this.deviceId)&&(ut===16?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),h=c*l;if(h&&r&&h===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:m.VIDEO,videoType:m.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return ei&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Rn()&&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,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(I.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(){ke&&!ke.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ke.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)}`),Te(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield _t();t[0]?this.recapture(t[0].deviceId):ke.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){ke.off("videoInputAdded",this.handleCameraAdded,this),ke.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Fe(Dr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield _t()).find(o=>o.deviceId!==e);if(r)yield Fe(Dr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};b([Ze(function(e){this.setContentHint(e.contentHint||"motion")})],Dr.prototype,"capture",1);var Je=Dr;var cm=go();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:cm,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var G_=function(s){return p(this,null,function*(){let i=null,e=j_(s);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(ds&<<74||Le||oe)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){R.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield W_(r,s.captureElement))}if(s.audio){let o=J_(s);R.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function W_(s,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&se(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===cm))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function J_(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return E(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function j_(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Le?{max:s.width}:{ideal:s.width,max:s.width},height:Le?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var dm=G_;var ct=class extends Je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(h){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let u;return a||n?(u=new MediaStream,a&&u.addTrack(a),n&&u.addTrack(n)):u=yield dm({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(u.getVideoTracks()[0]),u}catch(u){throw this.log.error(`getDisplayMedia error observed ${u}`),u instanceof y?u:new y({code:S.INITIALIZE_FAILED,name:u.name,message:u.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};b([Ze(function(e){this.setContentHint(e.contentHint||"detail")})],ct.prototype,"capture",1);var ci=class extends St{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var q_='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Kd;function Vo(s,i=48e3,e){return p(this,null,function*(){let t=Re("dump");Kd||(Kd=yr(t,URL.createObjectURL(new Blob([q_],{type:"application/javascript"})))),yield Kd;let r=t.sampleRate,o=new AudioWorkletNode(t,"dumper",{numberOfInputs:s.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:r,targetSampleRate:i}});return e&&o.port.postMessage({port:e},[e]),s.forEach((n,a)=>n.connect(o,0,a)),new ReadableStream({start(n){o.port.onmessage=a=>{n.enqueue(a.data)}},cancel(){s.forEach(n=>n.disconnect(o)),o.port.close()}})})}var ya=class extends ua{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",R.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var h,u;if(!this._localAudioTrack)return;let t=[],r=[];(h=this._localAudioPipline)!=null&&h.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(u=this._localAudioPipline)!=null&&u.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let f=0;f<r.length;f++){let g=URL.createObjectURL(new Blob(n[f])),D=document.createElement("a");D.href=g,D.download=`${r[f]}.pcm`,D.style.display="none",document.body.appendChild(D),D.click(),URL.revokeObjectURL(g),D.remove()}clearTimeout(a),o.abort("download")},l=Vo(t).then(f=>f.pipeTo(new WritableStream({write(g){g.forEach((D,_)=>n[_]=n[_]?n[_].concat(D[0]):[D[0]])}}),o).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var M,ne,F;if(E(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:o=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(o*.04),l=new Float32Array(c),h=new Float32Array(c),u,f,g=0,D=new AbortController,_=t===""?(M=this._localAudioTrack)==null?void 0:M.mediaTrack:(F=(ne=this.room)==null?void 0:ne.remotePublishedUserMap.get(t))==null?void 0:F.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Re().createMediaStreamSource(new MediaStream([_]));return Vo([C],o,a).then(Oe=>Oe.pipeTo(new WritableStream({write(U){U[0][0]&&(g+U[0][0].length>c?(l.set(U[0][0].subarray(0,c-g),g),u=U[0][0].subarray(c-g),h.set(U[0][1].subarray(0,c-g),g),f=U[0][1].subarray(c-g),g+=c-g):(u&&(l.set(u,g),g+=u.length,u=void 0),f&&(h.set(f,g),f=void 0),l.set(U[0][0],g),h.set(U[0][1],g),g+=U[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:o,channelCount:n,data:n===1?l:[l,h]}),l=new Float32Array(c),h=new Float32Array(c)))}}),D).catch(U=>this.log.warn(`stop getPCM reason:${U}`))),D}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){if(e instanceof ci)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof St)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof wi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof ci?delete this._localScreenAudioTrack:e instanceof St?delete this._localAudioTrack:e instanceof wi}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)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var o;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((o=this._localAudioTrack)==null||o.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(o=>{var n;(n=this.room)==null||n.emit("audio-frame",o)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){T.on("113",this.handleLocalTrackStarted,this),T.on("114",this.handleLocalTrackStopped,this),T.on("115",this.handleRemoteTrackStarted,this),T.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){T.off("113",this.handleLocalTrackStarted),T.off("114",this.handleLocalTrackStopped),T.off("115",this.handleRemoteTrackStarted),T.off("116",this.handleRemoteTrackStopped)}};function ba(s=30,i=2){return z((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new y({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});R.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var Ul={};fi(Ul,{Events:()=>Ie,Inspect:()=>It,LastSink:()=>Or,Sink:()=>W,Subscribe:()=>Mr,TimeoutError:()=>Bo,audit:()=>vg,bindCallback:()=>mg,bindNodeCallback:()=>pg,buffer:()=>ig,bufferCount:()=>tg,bufferTime:()=>qg,call:()=>lm,catchError:()=>Ll,combineLatest:()=>hm,concat:()=>Q_,concatMap:()=>Bg,concatMapTo:()=>Fg,count:()=>gg,create:()=>ee,debounce:()=>Dg,debounceTime:()=>Og,defer:()=>mm,delay:()=>Xg,deliver:()=>j,dispose:()=>Na,elementAt:()=>Mg,empty:()=>Ho,every:()=>xg,exhaustMap:()=>Gg,exhaustMapTo:()=>Wg,filter:()=>di,find:()=>kg,findIndex:()=>Lg,first:()=>Pg,fromAnimationFrame:()=>ug,fromArray:()=>og,fromEvent:()=>ue,fromEventPattern:()=>ng,fromFetch:()=>ag,fromIterable:()=>cg,fromPromise:()=>_m,fromReadableStream:()=>lg,fromReader:()=>dg,groupBy:()=>Jg,identity:()=>X_,ignoreElements:()=>Ig,iif:()=>K_,inspect:()=>um,interval:()=>ol,last:()=>wg,map:()=>Go,mapTo:()=>Vg,max:()=>Tg,merge:()=>rl,mergeMap:()=>$g,mergeMapTo:()=>Hg,min:()=>Eg,never:()=>fg,nothing:()=>ce,of:()=>sg,pairwise:()=>Ug,pipe:()=>de,race:()=>sl,range:()=>hg,reduce:()=>nl,retry:()=>Kg,scan:()=>kl,share:()=>xi,shareReplay:()=>Y_,skip:()=>Rg,skipUntil:()=>Cg,skipWhile:()=>ka,startWith:()=>Fo,subject:()=>et,subscribe:()=>Ce,sum:()=>Sg,switchMap:()=>As,switchMapTo:()=>Lr,take:()=>Ui,takeLast:()=>Ag,takeUntil:()=>xe,takeWhile:()=>gm,tap:()=>xl,throttle:()=>bg,throwError:()=>_g,timeInterval:()=>jg,timeout:()=>Yg,timer:()=>$o,toPromise:()=>zg,toReadableStream:()=>Qg,withLatestFrom:()=>eg,zip:()=>Z_});function ce(...s){}var lm=s=>s(),X_=s=>s;function Na(){this.dispose()}var um=()=>typeof __FASTRX_DEVTOOLS__!="undefined",z_=1,It=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Zd(i,this,this.streamId++);return Ie.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Or=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=ce,this.error=ce,this.next=ce,this.dispose=ce,this.subscribe=ce,this.doDefer()}subscribe(i){return i instanceof It?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(lm),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 Or{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)}},Mr=class extends Or{constructor(i,e=ce,t=ce,r=ce){if(super(),this._next=e,this._error=t,this._complete=r,this.then=ce,i instanceof It){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ie.defer(o,0)}),Ie.create(o),Ie.pipe(o),this.sourceId=o.id,this.subscribe(i),Ie.subscribe({id:o.id,end:!0}),e==ce?this._next=n=>Ie.next(o,0,n):this.next=n=>{Ie.next(o,0,n),e(n)},r==ce?this._complete=()=>Ie.complete(o,0):this.complete=()=>{this.dispose(),Ie.complete(o,0),r()},t==ce?this._error=n=>Ie.complete(o,0,n):this.error=n=>{this.dispose(),Ie.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function de(s,...i){return i.reduce((e,t)=>t(e),s)}function ee(s,i,e){if(um()){let t=Object.defineProperties(Object.setPrototypeOf(s,It.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}});Ie.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof It&&Ie.addSource(t,o)}return t}return s}function j(s,i){return function(...e){return t=>{if(t instanceof It){let r=ee(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Ie.pipe(r),r}else return r=>t(new s(r,...e))}}}function tr(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var Zd=class extends W{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ie.defer(this.source,this.id)})}next(i){Ie.next(this.source,this.id,i),this.sink.next(i)}complete(){Ie.complete(this.source,this.id),this.sink.complete()}error(i){Ie.complete(this.source,this.id,i),this.sink.error(i)}},Ie={addSource(s,i){tr("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){tr("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){tr("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){tr("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){tr("defer",{id:s.id,streamId:i})},pipe(s){tr("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){tr("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=z_++),tr("create",{name:s.toString(),id:s.id})}},Bo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var va=class extends Or{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 xi(){return s=>{let i=new va(s);if(s instanceof It){let e=ee(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Ie.pipe(e),e}return ee(i.add.bind(i),"share",arguments)}}function rl(...s){return ee(i=>{let e=new W(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function sl(...s){return ee(i=>{let e=new Map;s.forEach(t=>{let r=new W(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function Q_(...s){return ee(i=>{let e=0,t=s.length,r=new W(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function Y_(s){return i=>{let e=new va(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},ee(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function K_(s,i,e){return ee(t=>s()?i(t):e(t),"iif",arguments)}function hm(...s){return ee(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let h=new W(i);h.next=u=>{--t===0?(h.next=f=>{o[l]=f,i.next(o)},h.next(u)):o[l]=u},h.complete=n,h.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function Z_(...s){return ee(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new W(i),h=[];r[c]=h,l.next=u=>{h.push(u),r.every(f=>f.length)&&i.next(r.map(f=>f.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Fo(...s){return i=>ee((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var el=class extends W{constructor(i,...e){super(i);let t=new W(this.sink);t.next=r=>this.buffer=r,t.complete=ce,t.subscribe(hm(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},eg=j(el,"withLatestFrom"),tl=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()}},tg=j(tl,"bufferCount"),il=class extends W{constructor(i,e){super(i),this.buffer=[];let t=new W(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=ce,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},ig=j(il,"buffer");var rg=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(h){try{l(t.next(h))}catch(u){n(u)}}function c(h){try{l(t.throw(h))}catch(u){n(u)}}function l(h){h.done?o(h.value):r(h.value).then(a,c)}l((t=t.apply(s,i||[])).next())})};function et(s){let i=arguments,e=xi()(ee(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=ce,e.complete=ce,e.error=ce,e}function mm(s){return ee(i=>i.subscribe(s()),"defer",arguments)}var pm=s=>i=>{setTimeout(()=>s(i))},fm=s=>pm(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function sg(...s){return ee(fm(s),"of",arguments)}function og(s){return ee(fm(s),"fromArray",arguments)}function ol(s){return ee(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function $o(s,i){return ee(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function Da(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function ng(s,i){return ee(Da(s,i),"fromEventPattern",arguments)}function ue(s,i){if("on"in s&&"off"in s)return ee(Da(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return ee(Da(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return ee(Da(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function _m(s){return ee(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function ag(s,i){return ee(mm(()=>_m(fetch(s,i))),"fromFetch",arguments)}function cg(s){return ee(pm(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function dg(s){let i=e=>rg(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return ee(e=>{i(e)},"fromReader",arguments)}function lg(s){return ee(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function ug(){return ee(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function hg(s,i){return ee((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function mg(s,i,...e){return ee(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function pg(s,i,...e){return ee(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function fg(){return ee(()=>{},"never",arguments)}function _g(s){return ee(i=>i.error(s),"throwError",arguments)}function Ho(){return ee(s=>s.complete(),"empty",arguments)}var kr=class extends W{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},nl=j(kr,"reduce"),gg=s=>j(kr,"count")((i,e)=>s(e)?i+1:i,0),Tg=()=>j(kr,"max")(Math.max),Eg=()=>j(kr,"min")(Math.min),Sg=()=>j(kr,"sum")((s,i)=>s+i,0);var al=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)}},di=j(al,"filter"),cl=class extends W{next(i){}},Ig=j(cl,"ignoreElements"),dl=class extends W{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Ui=j(dl,"take"),ll=class extends W{constructor(i,e){super(i);let t=new W(i);t.next=()=>i.complete(),t.complete=Na,t.subscribe(e)}},xe=j(ll,"takeUntil"),ul=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},gm=j(ul,"takeWhile"),Ag=s=>nl((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),hl=class extends W{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},Rg=j(hl,"skip"),ml=class extends W{constructor(i,e){super(i),i.next=ce;let t=new W(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Na,t.subscribe(e)}},Cg=j(ml,"skipUntil"),pl=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ka=j(pl,"skipWhile"),yg={leading:!0,trailing:!1},fl=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)}},Oa=class extends W{constructor(i,e,t=yg){super(i),this.durationSelector=e,this.config=t,this._throttle=new fl(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=ce,this._throttle.complete(),super.complete()}},bg=j(Oa,"throttle"),Ng={leading:!1,trailing:!0},vg=s=>j(Oa,"audit")(s,Ng),_l=class extends W{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ma=class extends W{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new _l(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()}},Dg=j(Ma,"debounce"),Og=s=>j(Ma,"debounceTime")(i=>$o(s)),gl=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()}},Mg=j(gl,"elementAt"),kg=s=>i=>Ui(1)(ka(e=>!s(e))(i)),Tl=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}},Lg=j(Tl,"findIndex"),El=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()}},Pg=j(El,"first"),Sl=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()}},wg=j(Sl,"last"),Il=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()}},xg=j(Il,"every");var Al=class extends W{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},kl=j(Al,"scan"),Rl=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}},Ug=j(Rl,"pairwise"),La=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))}},Go=j(La,"map"),Vg=s=>j(La,"mapTo")(i=>s),Ss=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()}},Is=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()}},Pa=class extends Ss{},wa=class extends Is{next(i){this.subInner(i,Pa),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Pa)}}},As=j(wa,"switchMap");function Ba(s){return(i,e)=>s(()=>i,e)}var Lr=Ba(j(wa,"switchMapTo")),Cl=class extends Ss{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},xa=class extends Is{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(),Cl),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},Bg=j(xa,"concatMap"),Fg=Ba(j(xa,"concatMapTo")),yl=class extends Ss{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Ua=class extends Is{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,yl),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},$g=j(Ua,"mergeMap"),Hg=Ba(j(Ua,"mergeMapTo")),bl=class extends Ss{dispose(){this.context.resetNext(),super.dispose()}},Va=class extends Is{next(i){this.next=ce,this.subInner(i,bl)}},Gg=j(Va,"exhaustMap"),Wg=Ba(j(Va,"exhaustMapTo")),Nl=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=et(),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)}},Jg=j(Nl,"groupBy"),vl=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}},jg=j(vl,"timeInterval"),Dl=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()}},qg=j(Dl,"bufferTime"),Ol=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:r}=e;super.next(r),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)}},Xg=j(Ol,"delay"),Ml=class extends W{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Ll=j(Ml,"catchError");var zg=()=>s=>new Promise((i,e)=>{let t;new Mr(s,r=>t=r,e,()=>i(t))}),Qg=()=>s=>{let i;return new ReadableStream({start(e){i=new Mr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ce=(s=ce,i=ce,e=ce)=>t=>new Mr(t,s,i,e),Pl=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)}))}},xl=j(Pl,"tap"),wl=class extends W{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Bo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Yg=j(wl,"timeout"),Kg=(s=1/0)=>i=>{if(i instanceof It){let e=ee(t=>{let r=s,o=new W(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,Ie.pipe(e),e}else return e=>{let t=s,r=new W(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var li=class li extends Nr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",et(ue(this,li.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new H(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new H(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(rl(ue(this,H.STATECHANGED),ue(this.remotePublishState,H.STATECHANGED)),Go(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ce(c=>{this.availableState.state!==(c?H.ON:H.OFF)&&(this.availableState.state=c?H.ON:H.OFF),this.updatePlayingState(c)}));let o=de(ue(this.player,le.ERROR),di(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=de($o(5e3),di(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===m.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(sl(o,n),xe(ue(this,H.INIT)));de(this._triggerCheckDecodeSubject,di(()=>!this.ignoreDecodeError),Lr(a),Ce(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===li.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===H.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===m.AUDIO;N[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(N.addEnum({key:r?504701:514703,value:_o()}),te.uploadEvent({log:`stat-decode-failed-${this.kind}-${Tr()||bi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===m.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?H.ON:H.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(li,"STATE_SUBSCRIBE","subscribe"),b([ba(5,1)],li.prototype,"waitHasMediaTrack",1),b([pe(H.INIT,li.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(I.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),at(521716,!1)],li.prototype,"subscribe",1),b([pe(li.STATE_SUBSCRIBE,H.INIT,{sync:!0,success(){this.log.info("unsubscribed"),T.emit(I.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],li.prototype,"unsubscribe",1);var Rs=li;var wi=class extends Rs{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return br.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var eT=[-1,-1,1,-1,-1,1,1,1],tT=[0,0,1,0,0,1,1,1];var tt=class extends H{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof je){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&ut!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(tT),this.positionBuffer=this.createBuffer(eT),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}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 De&&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}update(e=0){var t;(t=this.output)==null||t.update(e)}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 De){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.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((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}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,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}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 r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.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 r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.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 r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var u;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,l=Date.now(),h=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:h,name:a,cost:c},v({parent:(u=this.input)==null?void 0:u.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),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),r}};b([pe(H.INIT,"connected",{sync:!0})],tt.prototype,"connect",1),b([pe("connected",H.INIT,{ignoreError:!0,sync:!0})],tt.prototype,"disconnect",1),b([pe([],"closed",{sync:!0})],tt.prototype,"close",1);var iT=de(ol(250),Go(()=>performance.now()),xi());var Em=s=>i=>{let e=performance.now();de(iT,ka(t=>t-e<s),Ui(1))(i)};var sT=[0,1,1,1,0,0,1,0],Pr=class extends tt{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof je?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(sT)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof De){let r=this.context.ctx.getError();r&&this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{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)}update(e=0){if(this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),re.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Cs=class extends Pr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ue(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Ci)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ue(this._videoTrack,"mute"),de(ue(this._videoTrack,"ended"),xe(this._closedOb),Ce(()=>{this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,xe(this._closedOb),Lr(Em(5e3)),di(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Ce(()=>{this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Fa=class extends Cs{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var $a=class extends Cs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Wo=class extends tt{constructor(e,t){super(e,v({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);d(this,"waitingFirstFrame",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,ut===16&&(this._canvasRendered=et(),de(this._canvasRendered,Fo(this._image),As(r=>r instanceof HTMLCanvasElement?ue(r,"rendered"):Ho()),xe(ue(this,"closed")),Ce(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Cr()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Jo=class extends Wo{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ue(this._player,le.PLAYER_STATE_CHANGED),xe(ue(this,"closed")),di(({state:o})=>o==="PLAYING"),Ce(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Vi=class extends Jo{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new pt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var nT=`
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Vd,r.innerText=`${Rt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${aa}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){$d()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${ms}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),ee.uploadEvent({log:I_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){C.warn("confirm clicked, try resume stream"),E.emit(T.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Uh}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ee.uploadEvent({log:A_}),this._isCollapseClicked=!0}onQuestionClick(){window.open($h,"_blank"),this._isQuestionClicked||ee.uploadEvent({log:C_}),this._isQuestionClicked=!0}},Hh=Bd;var ht=class extends ei{constructor(e){super(e,p.VIDEO);c(this,"stat",{});c(this,"_calculateTimeout",-1);c(this,"viewMirror",!1);c(this,"objectFit");c(this,"container");c(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,g(e.viewMirror)||(this.viewMirror=e.viewMirror),g(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(p.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var 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(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,o;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===p.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=cr,this._log.info(`view container ${(o=this.container)==null?void 0:o.id} is recreated`)),this._pausedRetryCount>0&&!$d()&&(this._log.info(`[${cr-this._pausedRetryCount+1}/${cr}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((o=this.element)==null||o.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}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}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(de.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ar()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function Cr(s,i){return f(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),C.info("worklet addModule success")}catch(e){throw C.info(`worklet addModule catch error. ${e.message}`),e}})}var ko;typeof AudioContext!="undefined"?ko=AudioContext:typeof webkitAudioContext!="undefined"?ko=webkitAudioContext:typeof mozAudioContext!="undefined"&&(ko=mozAudioContext);var Lt,Gh=-1;Wh();function Wh(){try{if(Lt)return;Lt=new ko({sampleRate:48e3}),Lt.onstatechange=()=>{C.info(`context state: ${Lt.state}${Lt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),ps()},clearTimeout(Gh)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof ko}`),Gh=setTimeout(Wh,1e3)}}var ps=()=>{Lt.state==="suspended"?(fs(),document.addEventListener("click",ps)):Lt.state==="interrupted"?fs():(document.removeEventListener("visibilitychange",ps),document.removeEventListener("click",ps))},Hd=0,Gd=-1;function fs(){return new Promise((s,i)=>{if(Lt.state==="running")return s();Date.now()-Hd<1e3?(clearTimeout(Gd),Gd=setTimeout(()=>{Hd=Date.now(),Lt.resume().then(s,i)},1e3)):(clearTimeout(Gd),Hd=Date.now(),Lt.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",ps)})}document.addEventListener("click",ps);var Le=s=>Lt;var $e=class{constructor(){c(this,"node");c(this,"node2");c(this,"pre",new Set);c(this,"next",new Set);c(this,"context");c(this,"connectedNodes",new Set);c(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){C.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),N.addSuccessEvent({key:502701})}catch(r){C.error(r),N.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),N.addSuccessEvent({key:502702})}catch(e){C.error(e),N.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.node2||this.node).connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||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}},da=class extends $e{constructor(e=256){super();this.fftSize=e;c(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,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Mo=class{constructor(){c(this,"source",new $e);c(this,"gain",new $e);c(this,"destination",new $e)}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(Le().createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.replaceNode(Wd(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}},_s=class extends Mo{constructor(e){super();this.context=e;c(this,"denoiser",new $e);c(this,"voiceChanger",new $e);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.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.voiceChanger.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.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.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}},la=class{constructor(){c(this,"audioContext",Le("audio-mixer"));c(this,"destination",this.audioContext.createMediaStreamDestination());c(this,"inputs",new Set);c(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]}},Jh=new WeakMap;function Wd(s){let i=Jh.get(s);if(i)return i;let e=Le();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return Jh.set(s,i),i}var mt=class mt{constructor(i){c(this,"_volume",0);c(this,"_volumeDb",0);c(this,"_log");c(this,"_scriptProcessorNode",null);c(this,"_audioWorkletNode",null);c(this,"_interval",200);c(this,"ready",this.preload());let{log:e}=i;this._log=e,E.on(T.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-mt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!mt.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';mt.workletReady=Cr(mt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return mt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(mt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{mt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ee.logFailedEvent({userId:this._log.userId,eventType:et.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Le("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{mt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];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,E.off(T.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};c(mt,"lastMessageTime",0),c(mt,"audioContext",Le("volume-meter")),c(mt,"workletReady");var ua=mt,ha=class extends $e{constructor(e){super();c(this,"_volumeMeter");this._volumeMeter=new ua(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},Rr=ua;var zh=Ue(qe(),1);var qh=s=>i=>i.deviceId===s;var Lo=class{constructor(i,e="Input"){c(this,"kind");c(this,"type");c(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&gs(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(qh(r.deviceId))){let o=`${this.kind}${this.type}Added`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(qh(r.deviceId))){let o=`${this.kind}${this.type}Removed`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Jd=class extends zh.EventEmitter{constructor(){super();c(this,"audioInputs",new Lo(p.AUDIO));c(this,"videoInputs",new Lo(p.VIDEO));c(this,"audioOutputs",new Lo(p.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run("interval",()=>{this.update()},{delay:1e4}))}init(){ma().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield ma(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},De=Hs||Hr?null:new Jd;function gs(s){return s.deviceId===s.groupId&&s.groupId===""}function ma(){return f(this,arguments,function*(s=0){if(bi()||!ta())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{gs(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&fs()}catch(r){C.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&jd.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function st(s=!1){return De.update(s?1:0).then(i=>i.audioInputs.devices)}function pt(s=!1){return De.update(s?2:0).then(i=>i.videoInputs.devices)}var Xh=!1;function Qh(){return f(this,null,function*(){try{Xh||(Xh=!0,C.info(`speakers:${(yield Yi()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function Yi(s=!1){return f(this,null,function*(){return(ge||Oe)&&(s=!1),De.update(s?1:0).then(i=>i.audioOutputs.devices)})}var jd=new Set;function Yh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!jd.has(t)}function Kh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!jd.has(t)}function qd(s,i){return f(this,null,function*(){let t=(yield st()).find(r=>r.deviceId===dr);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function Zh(o){return f(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===p.AUDIO&&s===dr?yield qd(e,t):!0})}var pa,Xd=class extends Mo{constructor(e){super();this.log=e;c(this,"volumeMeter");c(this,"volumeDestination");c(this,"analyser",new da);this.volumeMeter=new ha({log:this.log}),this.volumeDestination=new $e,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},fa=class s extends ei{constructor(e){super(e,p.AUDIO);c(this,"_outputDeviceId");c(this,"_volume",1);c(this,"_destination",Le("player").createMediaStreamDestination());c(this,"pipeline");c(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Xd(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((jt==="15.2"||jt==="15.3"||jt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=pa||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===pa&&(pa=void 0),this.bindElementEvents()}play(e){return f(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Le("player").createAnalyser()),Qh(),Ve(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.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()}},_a=class extends fa{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(de.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},ga=class extends fa{constructor(e){super(e);c(this,"_sourceElement");c(this,"_output",new $e);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(Le("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(de.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):ge||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Ce(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&ji&&(pa=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var yr=class extends B{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?ga:ht}){var a;super();c(this,"id",fo());c(this,"userId","");c(this,"isRemote");c(this,"mediaType");c(this,"room");c(this,"user");c(this,"_log");c(this,"_inputTrack");c(this,"_outputTrack");c(this,"isPlayCalled");c(this,"container",null);c(this,"player");c(this,"subVideoPlayerMap");c(this,"muted",!1);c(this,"abortCtrl");c(this,"objectFit","cover");c(this,"mirror");c(this,"isScreen",!1);c(this,"manager");c(this,"trackSettings");c(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=C.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Di?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Di}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(de.PLAYER_STATE_CHANGED,d=>{E.emit(T.PLAYER_STATE_CHANGED,v({track:this},d)),this.emit("player-state-changed",d)}),this.kind===p.VIDEO&&(this.player.on(de.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(de.LOADED_DATA),E.emit(T.VIDEO_LOADED_DATA,{track:this})}),this.player.on(de.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(de.LOADED_META_DATA)}),this.player.on(de.MEDIA_TRACK_CHANGED,d=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(d))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(de.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||C}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Se(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!g(t.muted)&&this.setPlayerMute(t.muted),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ht&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Se(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!g(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===p.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ht&&(this.player.setObjectFit(this.objectFit),t&&!g(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof ht&&this.player.setContainer(r)),E.emit(T.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(t),Se(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(fe(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(d=>n===d)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ht({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop($c(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),E.emit(e?T.TRACK_MUTED:T.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Fe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Ce(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop($c(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new Hh;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof ht?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,d;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((d=this.player.element)==null?void 0:d.videoHeight)||0;e===de.LOADED_META_DATA&&!r&&!o||(e===de.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:r,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};y([me([],B.INIT,{sync:!0})],yr.prototype,"close",1);var y_=Object.prototype.hasOwnProperty,{toString:tC}=Object.prototype;function b_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(tt(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(y_.call(s,i))return!1;return!0}}return!1}var ti=b_;var N_=function(s){return f(this,null,function*(){let i=D_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield st(),C.info(`microphones: ${_t(e.map(o=>M(v({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield pt(),C.info(`cameras: ${_t(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Dd&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${_t(n.getCapabilities(),{keysToInclude:En})}`)}),i.audio&&fs(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=U({key:x.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=U({key:x.MICROPHONE_NOT_FOUND}))),new b({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},v_=Wt({retryFunction:N_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!Oe||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&em(t[0].microphoneId,!1),t[0].cameraId&&em(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{ee.logFailedEvent({eventType:et.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{ee.logSuccessEvent({eventType:et.GET_USER_MEDIA_RETRY}),ee.uploadEvent({log:`stat-${et.GET_USER_MEDIA_RETRY}-success-${s}`})}});function em(s,i){return f(this,null,function*(){let t=(i?yield pt():yield st()).find(r=>r.deviceId===s);t&&ae(t.getCapabilities)&&C.warn(_t(t.getCapabilities(),{keysToInclude:En}))})}function D_(s){return{audio:O_(s),video:k_(s)}}function O_(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!ti(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(Q(s.channelCount)&&(i.channelCount=s.channelCount),fe(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),fe(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),fe(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),ti(i)?!0:i)}function k_(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!ti(e)?e:(s.width&&(e.width={ideal:s.width},i&&!se&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!se&&(e.height.max=s.height)),se&&Dt&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),ti(e)?!0:e)}var tm=v_;function Ta(s){return q((i,e)=>function(...t){return f(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Qe(s){return q((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function Ea(s){return q((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function q(s){return function(i,e,t){return t.value=s(t.value,e),t}}var im=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&C.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{C.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var M_=0,Sa=class{constructor(){c(this,"log",C.createLogger({id:`fq${++M_}`}));c(this,"isRunning",!1);c(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 o,n;let t=v({},i),r=new Promise((a,d)=>{t.resolve=a,t.reject=d});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}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:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Po=new WeakMap,Ia=new WeakMap;function ii(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=Po.get(this)||new Sa;return Po.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function rm(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=Po.get(this);if(n){let a=n.queue.filter((d,l)=>{if(l===0)return!0;let u=!0;return d.args.forEach(h=>{o.find(m=>m===h)||(u=!1)}),u?(d.reject(new b({code:S.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function Aa(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,d,l;let n=[];return(d=(a=Po.get(this))==null?void 0:a.queue)==null||d.forEach(u=>n.push(u)),(l=Ia.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new b({code:S.API_CALL_ABORTED,message:s}))}),Po.delete(this),Ia.delete(this),r.apply(this,o)},t}}function Oi(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Ia.get(this)||new Map,d=a.get(o(n))||new Sa;return a.set(o(n),d),Ia.set(this,a),d.push({fn:r,args:n,context:this})},t}}function ot(s,i){return q((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=L();return Wi(n)?n.then(d=>(i?N.addSuccessEvent({key:o,cost:L()-a}):N.addSuccessEvent({key:o}),d)).catch(d=>{throw N.addFailedEvent({key:o,error:d}),d}):(N.addSuccessEvent({key:o}),n)}catch(n){throw N.addFailedEvent({key:o,error:n}),n}})}var br=class br extends yr{constructor(e,t){super({mediaType:e,PlayerClass:t});c(this,"isRemote",!1);c(this,"deviceId");c(this,"groupId","");c(this,"label","");c(this,"sourceTrack");c(this,"_isRecapturing",!1);c(this,"_lastRecaptureTime",0);c(this,"_onMuteTimeoutId",-1);c(this,"_encodeCheckTimeoutId",-1);c(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Fe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Ce(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let r=L();E.emit(T.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield tm(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(T.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:L()-r}),o}catch(r){throw E.emit(T.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===B.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(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),E.emit(T.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&Qt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield Zh({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ma().then(n=>{let a=n.find(d=>d.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===p.AUDIO&&!Kh(this.mediaTrack)||this.kind===p.VIDEO&&!Yh(this.mediaTrack)||this._isRecapturing||e&&Dt&&Oe)}onTrackMuted(){if(super.onTrackMuted(),im(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Jr){setTimeout(()=>this.onTrackMuted(),Jr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((ge||ue)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Ve(br.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Jr){setTimeout(()=>this.onTrackEnded(),Jr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield st():yield pt()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),E.emit(T.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),E.emit(T.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof He;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(wo.get(t)||0)+1;if(wo.set(t,r),r>=3){let o=e?(yield pt()).find(n=>!wo.has(n.deviceId)):(yield st()).find(n=>!wo.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};y([me(B.INIT,"capture",{ignoreError:!0,sync:!0})],br.prototype,"setStateToCapture",1),y([ii()],br.prototype,"capture",1),y([me("capture","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),E.emit(T.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let d=this.kind===p.AUDIO,l=this.stat.bytesSent>0;N[l?"addSuccessEvent":"addFailedEvent"]({key:d?503700:513702}),l||(N.addEnum({key:d?503701:513703,value:po()}),ee.uploadEvent({log:`stat-encode-failed-${this.kind}-${fr()||Ai()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===S.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),ot(521714,!1)],br.prototype,"publish",1),y([q(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),me([],"capture",{sync:!0})],br.prototype,"unpublish",1);var Di=br,wo=new Map;E.on(T.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&wo.delete(s.track.deviceId)});var Tt=class s extends Di{constructor(e){super(1,_a);c(this,"mediaType",1);c(this,"volume",0);c(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});c(this,"playerMuted",!0);c(this,"pipeline");c(this,"earMonitorGainNode",new $e);c(this,"_output",new $e);c(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new _s(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Rr.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};N.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),N.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),N.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield Ve(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===dr){if(yield qd(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),E.emit(T.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(){De&&!De.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&De.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),_e(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield st();t[0]?this.recapture(t[0].deviceId):De.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),d=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,d=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,d=!0),!g(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,d=!0),d&&(se||Oe?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&N.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Le().createGain()),this._output.setNode(Le().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}addDenoiser(e){var t;if(ct<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}N.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),De.off("audioInputAdded",this.handleMicrophoneAdded,this),De.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ve(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield st()).find(o=>o.deviceId!==e);if(r)yield Ve(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var ki=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=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var Ca=class{constructor(){c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new ki(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,_)=>m+_.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),l=new DataView(d),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let _=0;_<n[m].dataView.byteLength;_++)l.setInt8(h++,n[m].dataView.getInt8(_));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=d,n.length}return 0}};var Nr=class Nr extends Di{constructor(e,t=4){super(t,ht);c(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});c(this,"avoidCropping",!1);c(this,"_scaleResolutionDownBy");c(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});c(this,"small");c(this,"isNeedToSetBandwidth");c(this,"muteImage");c(this,"manager");c(this,"_seiCodec",new Ca);this.manager=e;let r=()=>{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(v({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Qt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,r,o;if(K(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ve(Nr.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ve(Nr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){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:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=v({},e),r=t.width>t.height;t.width*t.height<=160*120&&ue&&Xe&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ed&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(Xe||se)&&!id()&&t.width*t.height<=640*360&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),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(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,o=this.settings;if(!(!(o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate)||!this.deviceId)&&(dt===16?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){this.isNeedToSetBandwidth=!1;let{width:d=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=d*l;if(u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return Qt&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:An()&&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 f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),E.emit(T.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(){De&&!De.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&De.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),_e(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield pt();t[0]?this.recapture(t[0].deviceId):De.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){De.off("videoInputAdded",this.handleCameraAdded,this),De.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ve(Nr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield pt()).find(o=>o.deviceId!==e);if(r)yield Ve(Nr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};y([Qe(function(e){this.setContentHint(e.contentHint||"motion")})],Nr.prototype,"capture",1);var He=Nr;var om=fo();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:om,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var x_=function(s){return f(this,null,function*(){let i=null,e=B_(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(as&&ct<74||Oe||se)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield U_(r,s.captureElement))}if(s.audio){let o=V_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function U_(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ae(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===om))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function V_(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return g(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function B_(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Oe?{max:s.width}:{ideal:s.width,max:s.width},height:Oe?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var nm=x_;var nt=class extends He{constructor(e){super(e,2);c(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});c(this,"objectFit","contain");c(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):h=yield nm({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:d,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof b?h:new b({code:S.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};y([Qe(function(e){this.setContentHint(e.contentHint||"detail")})],nt.prototype,"capture",1);var si=class extends Tt{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var F_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",zd;function xo(s){return f(this,null,function*(){let i=Le("dump");zd||(zd=Cr(i,URL.createObjectURL(new Blob([F_],{type:"application/javascript"})))),yield zd;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:s.length,numberOfOutputs:0});return s.forEach((t,r)=>t.connect(e,0,r)),new ReadableStream({start(t){e.port.onmessage=r=>{t.enqueue(r.data)}},cancel(){s.forEach(t=>t.disconnect(e)),e.port.close()}})})}var Ra=class extends la{constructor(e){super();this.room=e;c(this,"_localAudioTrack");c(this,"_localScreenAudioTrack");c(this,"log",C.createLogger({id:"am"}));c(this,"denoiser");c(this,"voiceChanger");c(this,"mixChangedDebounce");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),d=()=>{for(let m=0;m<r.length;m++){let _=URL.createObjectURL(new Blob(n[m])),I=document.createElement("a");I.href=_,I.download=`${r[m]}.pcm`,I.style.display="none",document.body.appendChild(I),I.click(),URL.revokeObjectURL(_),I.remove()}clearTimeout(a),o.abort("download")},l=xo(t).then(m=>m.pipeTo(new WritableStream({write(_){_.forEach((I,R)=>n[R]=n[R]?n[R].concat(I[0]):[I[0]])}}),o).catch(_=>d));return{then:l.then.bind(l),download:d}}getPCM(e){var n;if(g(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let t=new Float32Array(1920),r=0,o=new AbortController;return xo([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(d){d[0][0]&&(t.set(d[0][0],r),r+=d[0][0].length,r>=1920&&(r=0,e(t),t=new Float32Array(1920)))}}),o).catch(d=>this.log.warn(`stop getPCM reason:${d}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!g(this._localAudioTrack)}changeInput(e){if(e instanceof si)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof Tt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Mi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof si?delete this._localScreenAudioTrack:e instanceof Tt?delete this._localAudioTrack:e instanceof Mi}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)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function ya(s=30,i=2){return q((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let d=new b({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(d),i===2?n(d):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var Pl={};ui(Pl,{Events:()=>Te,Inspect:()=>Et,LastSink:()=>vr,Sink:()=>$,Subscribe:()=>Dr,TimeoutError:()=>Uo,audit:()=>Ig,bindCallback:()=>ng,bindNodeCallback:()=>ag,buffer:()=>z_,bufferCount:()=>X_,bufferTime:()=>Fg,call:()=>am,catchError:()=>Ol,combineLatest:()=>dm,concat:()=>G_,concatMap:()=>Mg,concatMapTo:()=>Lg,count:()=>lg,create:()=>Z,debounce:()=>Ag,debounceTime:()=>Cg,defer:()=>lm,delay:()=>$g,deliver:()=>G,dispose:()=>ba,elementAt:()=>Rg,empty:()=>Fo,every:()=>Dg,exhaustMap:()=>xg,exhaustMapTo:()=>Ug,filter:()=>oi,find:()=>yg,findIndex:()=>bg,first:()=>Ng,fromAnimationFrame:()=>sg,fromArray:()=>K_,fromEvent:()=>le,fromEventPattern:()=>Z_,fromFetch:()=>eg,fromIterable:()=>tg,fromPromise:()=>mm,fromReadableStream:()=>rg,fromReader:()=>ig,groupBy:()=>Vg,identity:()=>$_,ignoreElements:()=>pg,iif:()=>J_,inspect:()=>cm,interval:()=>il,last:()=>vg,map:()=>$o,mapTo:()=>kg,max:()=>ug,merge:()=>el,mergeMap:()=>Pg,mergeMapTo:()=>wg,min:()=>hg,never:()=>cg,nothing:()=>ne,of:()=>Y_,pairwise:()=>Og,pipe:()=>ce,race:()=>tl,range:()=>og,reduce:()=>rl,retry:()=>Jg,scan:()=>Dl,share:()=>Li,shareReplay:()=>W_,skip:()=>_g,skipUntil:()=>gg,skipWhile:()=>ka,startWith:()=>Vo,subject:()=>Ye,subscribe:()=>Ie,sum:()=>mg,switchMap:()=>Ss,switchMapTo:()=>kr,take:()=>Pi,takeLast:()=>fg,takeUntil:()=>Pe,takeWhile:()=>pm,tap:()=>Ll,throttle:()=>Eg,throwError:()=>dg,timeInterval:()=>Bg,timeout:()=>Wg,timer:()=>Bo,toPromise:()=>Hg,toReadableStream:()=>Gg,withLatestFrom:()=>q_,zip:()=>j_});function ne(...s){}var am=s=>s(),$_=s=>s;function ba(){this.dispose()}var cm=()=>typeof __FASTRX_DEVTOOLS__!="undefined",H_=1,Et=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Qd(i,this,this.streamId++);return Te.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},vr=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=ne,this.error=ne,this.next=ne,this.dispose=ne,this.subscribe=ne,this.doDefer()}subscribe(i){return i instanceof Et?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(am),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}},$=class extends vr{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)}},Dr=class extends vr{constructor(i,e=ne,t=ne,r=ne){if(super(),this._next=e,this._error=t,this._complete=r,this.then=ne,i instanceof Et){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Te.defer(o,0)}),Te.create(o),Te.pipe(o),this.sourceId=o.id,this.subscribe(i),Te.subscribe({id:o.id,end:!0}),e==ne?this._next=n=>Te.next(o,0,n):this.next=n=>{Te.next(o,0,n),e(n)},r==ne?this._complete=()=>Te.complete(o,0):this.complete=()=>{this.dispose(),Te.complete(o,0),r()},t==ne?this._error=n=>Te.complete(o,0,n):this.error=n=>{this.dispose(),Te.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function ce(s,...i){return i.reduce((e,t)=>t(e),s)}function Z(s,i,e){if(cm()){let t=Object.defineProperties(Object.setPrototypeOf(s,Et.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}});Te.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof Et&&Te.addSource(t,o)}return t}return s}function G(s,i){return function(...e){return t=>{if(t instanceof Et){let r=Z(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Te.pipe(r),r}else return r=>t(new s(r,...e))}}}function Ki(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var Qd=class extends ${constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Te.defer(this.source,this.id)})}next(i){Te.next(this.source,this.id,i),this.sink.next(i)}complete(){Te.complete(this.source,this.id),this.sink.complete()}error(i){Te.complete(this.source,this.id,i),this.sink.error(i)}},Te={addSource(s,i){Ki("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){Ki("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){Ki("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){Ki("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){Ki("defer",{id:s.id,streamId:i})},pipe(s){Ki("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){Ki("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=H_++),Ki("create",{name:s.toString(),id:s.id})}},Uo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Na=class extends vr{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 Li(){return s=>{let i=new Na(s);if(s instanceof Et){let e=Z(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Te.pipe(e),e}return Z(i.add.bind(i),"share",arguments)}}function el(...s){return Z(i=>{let e=new $(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function tl(...s){return Z(i=>{let e=new Map;s.forEach(t=>{let r=new $(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function G_(...s){return Z(i=>{let e=0,t=s.length,r=new $(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function W_(s){return i=>{let e=new Na(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},Z(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function J_(s,i,e){return Z(t=>s()?i(t):e(t),"iif",arguments)}function dm(...s){return Z(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(d,l)=>{let u=new $(i);u.next=h=>{--t===0?(u.next=m=>{o[l]=m,i.next(o)},u.next(h)):o[l]=h},u.complete=n,u.subscribe(d)};s.forEach(a)},"combineLatest",arguments)}function j_(...s){return Z(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,d)=>{let l=new $(i),u=[];r[d]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Vo(...s){return i=>Z((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Yd=class extends ${constructor(i,...e){super(i);let t=new $(this.sink);t.next=r=>this.buffer=r,t.complete=ne,t.subscribe(dm(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},q_=G(Yd,"withLatestFrom"),Kd=class extends ${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()}},X_=G(Kd,"bufferCount"),Zd=class extends ${constructor(i,e){super(i),this.buffer=[];let t=new $(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=ne,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},z_=G(Zd,"buffer");var Q_=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function d(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?o(u.value):r(u.value).then(a,d)}l((t=t.apply(s,i||[])).next())})};function Ye(s){let i=arguments,e=Li()(Z(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=ne,e.complete=ne,e.error=ne,e}function lm(s){return Z(i=>i.subscribe(s()),"defer",arguments)}var um=s=>i=>{setTimeout(()=>s(i))},hm=s=>um(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function Y_(...s){return Z(hm(s),"of",arguments)}function K_(s){return Z(hm(s),"fromArray",arguments)}function il(s){return Z(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Bo(s,i){return Z(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function va(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function Z_(s,i){return Z(va(s,i),"fromEventPattern",arguments)}function le(s,i){if("on"in s&&"off"in s)return Z(va(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return Z(va(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return Z(va(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function mm(s){return Z(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function eg(s,i){return Z(lm(()=>mm(fetch(s,i))),"fromFetch",arguments)}function tg(s){return Z(um(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function ig(s){let i=e=>Q_(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return Z(e=>{i(e)},"fromReader",arguments)}function rg(s){return Z(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function sg(){return Z(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function og(s,i){return Z((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function ng(s,i,...e){return Z(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function ag(s,i,...e){return Z(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function cg(){return Z(()=>{},"never",arguments)}function dg(s){return Z(i=>i.error(s),"throwError",arguments)}function Fo(){return Z(s=>s.complete(),"empty",arguments)}var Or=class extends ${constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},rl=G(Or,"reduce"),lg=s=>G(Or,"count")((i,e)=>s(e)?i+1:i,0),ug=()=>G(Or,"max")(Math.max),hg=()=>G(Or,"min")(Math.min),mg=()=>G(Or,"sum")((s,i)=>s+i,0);var sl=class extends ${constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},oi=G(sl,"filter"),ol=class extends ${next(i){}},pg=G(ol,"ignoreElements"),nl=class extends ${constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Pi=G(nl,"take"),al=class extends ${constructor(i,e){super(i);let t=new $(i);t.next=()=>i.complete(),t.complete=ba,t.subscribe(e)}},Pe=G(al,"takeUntil"),cl=class extends ${constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},pm=G(cl,"takeWhile"),fg=s=>rl((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),dl=class extends ${constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},_g=G(dl,"skip"),ll=class extends ${constructor(i,e){super(i),i.next=ne;let t=new $(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=ba,t.subscribe(e)}},gg=G(ll,"skipUntil"),ul=class extends ${constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ka=G(ul,"skipWhile"),Tg={leading:!0,trailing:!1},hl=class extends ${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)}},Da=class extends ${constructor(i,e,t=Tg){super(i),this.durationSelector=e,this.config=t,this._throttle=new hl(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=ne,this._throttle.complete(),super.complete()}},Eg=G(Da,"throttle"),Sg={leading:!1,trailing:!0},Ig=s=>G(Da,"audit")(s,Sg),ml=class extends ${next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Oa=class extends ${constructor(i,e){super(i),this.durationSelector=e,this._debounce=new ml(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()}},Ag=G(Oa,"debounce"),Cg=s=>G(Oa,"debounceTime")(i=>Bo(s)),pl=class extends ${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()}},Rg=G(pl,"elementAt"),yg=s=>i=>Pi(1)(ka(e=>!s(e))(i)),fl=class extends ${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}},bg=G(fl,"findIndex"),_l=class extends ${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()}},Ng=G(_l,"first"),gl=class extends ${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()}},vg=G(gl,"last"),Tl=class extends ${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()}},Dg=G(Tl,"every");var El=class extends ${constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},Dl=G(El,"scan"),Sl=class extends ${constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},Og=G(Sl,"pairwise"),Ma=class extends ${constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},$o=G(Ma,"map"),kg=s=>G(Ma,"mapTo")(i=>s),Ts=class extends ${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()}},Es=class extends ${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()}},La=class extends Ts{},Pa=class extends Es{next(i){this.subInner(i,La),this.next=e=>{this.currentSink.dispose(),this.subInner(e,La)}}},Ss=G(Pa,"switchMap");function Va(s){return(i,e)=>s(()=>i,e)}var kr=Va(G(Pa,"switchMapTo")),Il=class extends Ts{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},wa=class extends Es{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(),Il),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},Mg=G(wa,"concatMap"),Lg=Va(G(wa,"concatMapTo")),Al=class extends Ts{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},xa=class extends Es{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Al),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},Pg=G(xa,"mergeMap"),wg=Va(G(xa,"mergeMapTo")),Cl=class extends Ts{dispose(){this.context.resetNext(),super.dispose()}},Ua=class extends Es{next(i){this.next=ne,this.subInner(i,Cl)}},xg=G(Ua,"exhaustMap"),Ug=Va(G(Ua,"exhaustMapTo")),Rl=class extends ${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=Ye(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},Vg=G(Rl,"groupBy"),yl=class extends ${constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},Bg=G(yl,"timeInterval"),bl=class extends ${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()}},Fg=G(bl,"bufferTime"),Nl=class extends ${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:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},$g=G(Nl,"delay"),vl=class extends ${constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Ol=G(vl,"catchError");var Hg=()=>s=>new Promise((i,e)=>{let t;new Dr(s,r=>t=r,e,()=>i(t))}),Gg=()=>s=>{let i;return new ReadableStream({start(e){i=new Dr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ie=(s=ne,i=ne,e=ne)=>t=>new Dr(t,s,i,e),kl=class extends ${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)}))}},Ll=G(kl,"tap"),Ml=class extends ${constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Uo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Wg=G(Ml,"timeout"),Jg=(s=1/0)=>i=>{if(i instanceof Et){let e=Z(t=>{let r=s,o=new $(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,Te.pipe(e),e}else return e=>{let t=s,r=new $(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var ni=class ni extends yr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;c(this,"tinyId");c(this,"isRemote",!0);c(this,"jitterBufferDelay",0);c(this,"availableState");c(this,"remotePublishState");c(this,"_triggerCheckDecodeSubject",Ye(le(this,ni.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new B(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new B(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ce(el(le(this,B.STATECHANGED),le(this.remotePublishState,B.STATECHANGED)),$o(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ie(d=>{this.availableState.state!==(d?B.ON:B.OFF)&&(this.availableState.state=d?B.ON:B.OFF),this.updatePlayingState(d)}));let o=ce(le(this.player,de.ERROR),oi(d=>d.code===MediaError.MEDIA_ERR_DECODE)),n=ce(Bo(5e3),oi(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ce(tl(o,n),Pe(le(this,B.INIT)));ce(this._triggerCheckDecodeSubject,oi(()=>!this.ignoreDecodeError),kr(a),Ie(d=>{this.reportDecodeResult(!1,d)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ni.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===B.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===p.AUDIO;N[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(N.addEnum({key:r?504701:514703,value:po()}),ee.uploadEvent({log:`stat-decode-failed-${this.kind}-${fr()||Ai()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?B.ON:B.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};c(ni,"STATE_SUBSCRIBE","subscribe"),y([ya(5,1)],ni.prototype,"waitHasMediaTrack",1),y([me(B.INIT,ni.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),E.emit(T.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),ot(521716,!1)],ni.prototype,"subscribe",1),y([me(ni.STATE_SUBSCRIBE,B.INIT,{sync:!0,success(){this.log.info("unsubscribed"),E.emit(T.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ni.prototype,"unsubscribe",1);var Is=ni;var Mi=class extends Is{constructor(e,t){super(e,t,1);c(this,"volume",0);c(this,"mediaType",1);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Rr.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var qg=[-1,-1,1,-1,-1,1,1,1],Xg=[0,0,1,0,0,1,1,1];var Ke=class extends B{constructor(e,t){super();this.context=e;c(this,"name");c(this,"input");c(this,"output");c(this,"texture");c(this,"ctx2d",null);c(this,"fbo");c(this,"width",0);c(this,"height",0);c(this,"x",0);c(this,"y",0);c(this,"program");c(this,"vertexShader");c(this,"fragmentShader");c(this,"totalFrames",0);c(this,"dropFrames",0);c(this,"matchInputSize",!0);c(this,"texCoordBuffer");c(this,"positionBuffer");c(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});c(this,"cost",0);c(this,"_canvas",null);c(this,"_image");c(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Ge){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&dt!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(Xg),this.positionBuffer=this.createBuffer(qg),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}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 Ne&&this.render(e)||this.context instanceof Ge&&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}update(e=0){var t;(t=this.output)==null||t.update(e)}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 Ne){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.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((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}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,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}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 r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.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 r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.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 r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:d}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:u,name:a,cost:d},v({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),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),r}};y([me(B.INIT,"connected",{sync:!0})],Ke.prototype,"connect",1),y([me("connected",B.INIT,{ignoreError:!0,sync:!0})],Ke.prototype,"disconnect",1),y([me([],"closed",{sync:!0})],Ke.prototype,"close",1);var zg=ce(il(250),$o(()=>performance.now()),Li());var _m=s=>i=>{let e=performance.now();ce(zg,ka(t=>t-e<s),Pi(1))(i)};var Yg=[0,1,1,1,0,0,1,0],Mr=class extends Ke{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));c(this,"_intervalId",0);c(this,"_sequence",0);c(this,"checkGLError",!1);c(this,"checkVisibilityChange");e instanceof Ge?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(Yg)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Ne){let r=this.context.ctx.getError();r&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{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)}update(e=0){if(this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),re.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},As=class extends Mr{constructor(e,t){super(e,t);c(this,"_videoTrack");c(this,"_muteOb");c(this,"_closedOb",le(this,"closed"));c(this,"_subscription");c(this,"_canvasContainer");Number(Si)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=le(this._videoTrack,"mute"),ce(le(this._videoTrack,"ended"),Pe(this._closedOb),Ie(()=>{this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ce(this._muteOb,Pe(this._closedOb),kr(_m(5e3)),oi(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Ie(()=>{this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Ba=class extends As{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Fa=class extends As{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Ho=class extends Ke{constructor(e,t){super(e,v({name:"imageSource"},t));c(this,"_lastImage");c(this,"_totalFrames",0);c(this,"_autoResize",!1);c(this,"_canvasRendered");c(this,"_videoCallbackId",0);c(this,"waitingFirstFrame",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,dt===16&&(this._canvasRendered=Ye(),ce(this._canvasRendered,Vo(this._image),Ss(r=>r instanceof HTMLCanvasElement?le(r,"rendered"):Fo()),Pe(le(this,"closed")),Ie(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Ar()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let d=this.context.ctx;d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let d=this.context.ctx;d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Go=class extends Ho{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",ce(le(this._player,de.PLAYER_STATE_CHANGED),Pe(le(this,"closed")),oi(({state:o})=>o==="PLAYING"),Ie(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},wi=class extends Go{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new ht({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Zg=`
|
|
34
34
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
35
35
|
attribute vec4 a_position;
|
|
36
36
|
attribute vec2 a_texCoord;
|
|
@@ -40,7 +40,7 @@ void main() {
|
|
|
40
40
|
gl_Position = a_position;
|
|
41
41
|
v_texCoord = a_texCoord;
|
|
42
42
|
}
|
|
43
|
-
`,
|
|
43
|
+
`,eT=`
|
|
44
44
|
// \u7247\u5143\u7740\u8272\u5668
|
|
45
45
|
precision mediump float;
|
|
46
46
|
varying vec2 v_texCoord;
|
|
@@ -48,32 +48,32 @@ uniform sampler2D u_texture;
|
|
|
48
48
|
|
|
49
49
|
void main() {
|
|
50
50
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
51
|
-
} `;var wr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Vi(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Cs(this,e)}createVideoImageSource(e,t){return new Wo(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Jo(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(wr,"_ids",0);var cT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ys=class ys extends wr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${wr._ids++}`),this.ctx=this._canvas.getContext("webgl2",cT),!this.ctx)throw new y({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,nT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,aT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,N.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),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 r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(ys,"UNAVAILABLE","unavailable"),b([pe(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),N.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),N.addSuccessEvent({key:512700})}})],ys.prototype,"create",1),b([pe("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(ys.UNAVAILABLE,e),this.removeAllListeners()}})],ys.prototype,"destroy",1);var De=ys,je=class extends wr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${wr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,N.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),N.addSuccessEvent({key:512703})}};b([pe(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),N.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),N.addSuccessEvent({key:512701})}})],je.prototype,"create",1),b([pe("created",H.INIT,{ignoreError:!0,sync:!0})],je.prototype,"destroy",1);function dT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var ui=class extends Rs{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(ge(t==null?void 0:t.canvasRender)?t.canvasRender:ut===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new je({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Pr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Cr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=dT(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},bs=class extends ui{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ns=new Map;T.on(I.JOIN_SUCCESS,({room:s})=>{Te(s.userId,{eventId:32788})});T.on(I.LEAVE_START,({room:s})=>{Te(s.userId,{eventId:32789})});T.on(I.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Te(s.room.userId,{eventId:i})}});T.on(I.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Te(s.room.userId,{eventId:i})}});T.on(I.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?Te(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Te(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});T.on(I.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?Te(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Te(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});T.on(I.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Te(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Te(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Te(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});T.on(I.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Te(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Te(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Te(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});T.on(I.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Te(s.room.userId,{eventId:s.kind===m.VIDEO?32780:32781})});T.on(I.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Te(s.room.userId,{eventId:s.kind===m.VIDEO?32782:32783})});T.on(I.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Te(s.userId,{eventId:t})});T.on(I.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Te(s.userId,{eventId:o,remoteUserId:t})});T.on(I.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Te(i,l),N.addEnum({key:e?514701:513701,value:a}),N.addEnum({key:e?514700:513700,value:c})});T.on(I.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===m.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Te(s.userId,e)}});function Te(s,i){let e=w(v({},i),{timestamp:Hs()});Ns.has(s)?Ns.get(s).push(e):Ns.set(s,[e])}function Sm(s){if(Ns.has(s)){let i=Ns.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Ns.delete(s),i}return[]}function Im(...s){return z((i,e)=>function(...t){return lT.call(this,s,t,e,this._name),i.apply(this,t)})}function lT(s,i,e,t){try{if(_e(s))for(let r=0;r<s.length;r++)Ha.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Ha.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function Ha({rule:s,value:i,key:e,fnName:t,className:r}){if(E(i)){if(s.required)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(E(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),se(s.type[c])&&i instanceof s.type[c]&&(a=!0),K(s.type[c])&&Ee(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>fr(c)?Xr(c):K(c)?c:Ee(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(s.type)&&Ee(i)!==s.type)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),c=K(i)&&i.trim()==="";if(a||c)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&Q(i)&&i<0)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(s.min)&&Q(i)&&i<s.min)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(s.max)&&Q(i)&&i>s.max)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(se(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;He(o)&&bt(i)&&Object.keys(o).forEach(a=>{Ha.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;He(n)&&_e(i)&&i.forEach((a,c)=>{Ha.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),se(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Am=Be(Qe(),1);var Ga=class extends Am.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;E(t)||(o+=`:${Uc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[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 r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=Si(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Si(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Bl({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return z((t,r)=>{let o=new WeakMap;return T.on(I.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new y({code:S.INVALID_OPERATION,message:P({key:L.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var uT="2025-05-27 12:29:27",Rm=!0,Cm=function(){var s;if(Rm){Rm=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ht}/en/index.html`),console.info(`* Changelog: ${Ht}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",Me),Lt||R.debug("Build Time:",uT);let i=`UA: ${navigator.userAgent}
|
|
52
|
-
CPU core: ${navigator.hardwareConcurrency}, GPU: ${nd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),fo().then(t=>{t&&R.info(Dt)})}};var At={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var $={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},Ut=(A=>(A[A.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",A[A.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",A[A.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",A[A.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",A[A.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",A[A.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",A[A.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",A[A.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",A[A.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",A[A.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",A[A.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",A[A.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",A[A.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",A[A.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",A[A.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",A[A.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",A[A.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",A[A.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",A[A.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",A[A.INVALID_OPERATION=5100]="INVALID_OPERATION",A[A.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",A[A.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",A[A.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",A[A.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",A[A.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",A[A.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",A[A.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",A[A.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",A[A.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",A[A.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",A[A.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",A[A.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",A[A.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",A[A.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",A[A.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",A[A.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",A[A.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",A[A.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",A[A.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",A[A.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",A[A.DEVICE_ERROR=5300]="DEVICE_ERROR",A[A.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",A[A.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",A[A.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",A[A.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",A[A.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",A[A.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",A[A.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",A[A.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",A[A.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",A[A.SERVER_ERROR=5400]="SERVER_ERROR",A[A.NEED_TO_BUY=5401]="NEED_TO_BUY",A[A.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",A[A.OPERATION_FAILED=5500]="OPERATION_FAILED",A[A.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",A[A.REJOIN_FAILED=5502]="REJOIN_FAILED",A[A.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",A[A.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",A[A.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",A[A.OPERATION_ABORT=5998]="OPERATION_ABORT",A[A.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",A))(Ut||{});function bm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Ut[s];try{r=ym[o]}catch(n){r=ym.UNKNOWN_ERROR}return se(r)?t=r(i):K(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var ym=w(v({},we),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ee(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ee(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' 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:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' 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:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=xr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=xr(s),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:s,deviceType:i=xr(s),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:s,deviceType:i=xr(s),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:s,deviceType:i=xr(s),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:s,deviceType:i=xr(s),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:s,deviceType:i=xr(s),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:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' 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:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function xr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Fl=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=bm({code:e===$.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=Ut[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},f=document.createElement("a");gr?f.href=`ms-settings:privacy-${u[this.functionName]}`:kt&&(f.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),f.href.length>0&&f.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof y){let{stack:n}=e,a={code:$.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=$.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=$.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=$.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(we.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=$.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=$.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=hT(e.name));break;case S.UNKNOWN:break;default:a.code=$.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
53
|
-
`)))}else{if(e instanceof s)return e;o=new s({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function hT(s){let i;switch(s){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 B=Fl;var Nm={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}}},vm={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}}},vs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(K(s)&&!document.getElementById(s))throw new B({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Dm={name:"userId",required:!0,type:"string"},Om={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[At.AUDIO_PROFILE_STANDARD,At.AUDIO_PROFILE_STANDARD_STEREO,At.AUDIO_PROFILE_HIGH,At.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function jo(s,i){if(!s)throw new B({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Mm(s,i,e){if(!s)throw new B({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var oO={type:"number",notLessThanZero:!0},mT={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new B({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(K(s.roomId))throw new B({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new B({code:$.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new B({code:$.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new B({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:vs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Nm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Di())throw new B({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(v({},vs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Nm}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Om},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Di())throw new B({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Om}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:vs,publish:{type:"boolean"},option:vm},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(Di())throw new B({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ao())throw new B({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:vs,publish:{type:"boolean"},option:vm}},muteRemoteAudio:[Dm,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Dm,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:vs,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(s,i,e){jo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Mm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new B({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(v({},vs),{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(s,i,e){jo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Mm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new B({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&E(s.streamType))throw new B({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){jo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!bo)throw new B({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new B({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new B({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new B({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});jo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new B({code:$.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new B({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new B({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(jo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new B({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ue={TRTC:mT};var qe=class extends Error{};function pT(s,i){let e=hr(s);for(let t=0;t<i.length;t++)Wt(e[t],i[t]);return e}function fT(s){this._resolve=Promise.resolve(s)}function _T(s){this._reject=Promise.reject(s)}var ir=class ir{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",pT);let t=ir.instances.get(i);t?t.set(e,this):ir.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=ir.instances.get(i);return t&&t.get(e)||new ir(i,e)}static gets(i,e){let t=ir.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new qe("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:fT,reject:_T};try{switch(this.state){case 1:if(i===0)throw new qe("already started");break;case 4:if(i===2)throw new qe("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new qe("already start");break;case 3:switch(i.type){case 2:throw new qe("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new qe("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new qe("keep stop");if(this.ops.slice(1).forEach(r=>r.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 qe("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new qe("start not allowed after update");case 0:throw new qe("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new qe("keep start")),new qe("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});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}};d(ir,"instances",new WeakMap);var Bi=ir;var Wa=new WeakMap,Ja=(s,i)=>{if(i instanceof qe){let{stack:e}=i;i=new B({code:$.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
54
|
-
`)))}throw i};function
|
|
55
|
-
`));function
|
|
51
|
+
} `;var Lr=class extends B{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new wi(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new As(this,e)}createVideoImageSource(e,t){return new Ho(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Go(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(Lr,"_ids",0);var tT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Cs=class Cs extends Lr{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Lr._ids++}`),this.ctx=this._canvas.getContext("webgl2",tT),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Zg),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,eT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,N.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),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 r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};c(Cs,"UNAVAILABLE","unavailable"),y([me(B.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),N.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),N.addSuccessEvent({key:512700})}})],Cs.prototype,"create",1),y([me("created",B.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Cs.UNAVAILABLE,e),this.removeAllListeners()}})],Cs.prototype,"destroy",1);var Ne=Cs,Ge=class extends Lr{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Lr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,N.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),N.addSuccessEvent({key:512703})}};y([me(B.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),N.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),N.addSuccessEvent({key:512701})}})],Ge.prototype,"create",1),y([me("created",B.INIT,{ignoreError:!0,sync:!0})],Ge.prototype,"destroy",1);function iT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var ai=class extends Is{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(fe(t==null?void 0:t.canvasRender)?t.canvasRender:dt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Ge({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Mr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Ar()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=iT(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Rs=class extends ai{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ys=new Map;E.on(T.JOIN_SUCCESS,({room:s})=>{_e(s.userId,{eventId:32788})});E.on(T.LEAVE_START,({room:s})=>{_e(s.userId,{eventId:32789})});E.on(T.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),_e(s.room.userId,{eventId:i})}});E.on(T.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),_e(s.room.userId,{eventId:i})}});E.on(T.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?_e(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):_e(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(T.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?_e(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):_e(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(T.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&_e(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&_e(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&_e(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(T.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&_e(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&_e(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&_e(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(T.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&_e(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(T.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&_e(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(T.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&_e(s.userId,{eventId:t})});E.on(T.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&_e(s.userId,{eventId:o,remoteUserId:t})});E.on(T.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let d=t==="h264"?0:2,l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),_e(i,l),N.addEnum({key:e?514701:513701,value:a}),N.addEnum({key:e?514700:513700,value:d})});E.on(T.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),_e(s.userId,e)}});function _e(s,i){let e=M(v({},i),{timestamp:Fs()});ys.has(s)?ys.get(s).push(e):ys.set(s,[e])}function gm(s){if(ys.has(s)){let i=ys.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ys.delete(s),i}return[]}var Tm=Ue(qe(),1);var $a=class extends Tm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;g(t)||(o+=`:${Pc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[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 r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,d=_i(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==o&&(h.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:_i(0,n),muteState:d,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function xl({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return q((t,r)=>{let o=new WeakMap;return E.on(T.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new b({code:S.INVALID_OPERATION,message:U({key:x.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var rT="2025-05-27 19:35:36",Em=!0,Sm=function(){var s;if(Em){Em=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Bt}/en/index.html`),console.info(`* Changelog: ${Bt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",ve),Ot||C.debug("Build Time:",rT);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
CPU core: ${navigator.hardwareConcurrency}, GPU: ${rd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),mo().then(t=>{t&&C.info(bt)})}};var St={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var V={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},Pt=(A=>(A[A.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",A[A.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",A[A.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",A[A.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",A[A.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",A[A.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",A[A.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",A[A.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",A[A.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",A[A.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",A[A.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",A[A.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",A[A.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",A[A.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",A[A.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",A[A.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",A[A.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",A[A.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",A[A.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",A[A.INVALID_OPERATION=5100]="INVALID_OPERATION",A[A.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",A[A.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",A[A.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",A[A.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",A[A.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",A[A.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",A[A.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",A[A.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",A[A.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",A[A.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",A[A.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",A[A.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",A[A.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",A[A.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",A[A.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",A[A.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",A[A.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",A[A.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",A[A.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",A[A.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",A[A.DEVICE_ERROR=5300]="DEVICE_ERROR",A[A.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",A[A.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",A[A.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",A[A.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",A[A.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",A[A.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",A[A.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",A[A.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",A[A.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",A[A.SERVER_ERROR=5400]="SERVER_ERROR",A[A.NEED_TO_BUY=5401]="NEED_TO_BUY",A[A.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",A[A.OPERATION_FAILED=5500]="OPERATION_FAILED",A[A.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",A[A.REJOIN_FAILED=5502]="REJOIN_FAILED",A[A.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",A[A.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",A[A.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",A[A.OPERATION_ABORT=5998]="OPERATION_ABORT",A[A.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",A))(Pt||{});function Am({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Pt[s];try{r=Im[o]}catch(n){r=Im.UNKNOWN_ERROR}return ae(r)?t=r(i):K(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Im=M(v({},Me),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' 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:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' 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:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=Pr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=Pr(s),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:s,deviceType:i=Pr(s),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:s,deviceType:i=Pr(s),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:s,deviceType:i=Pr(s),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:s,deviceType:i=Pr(s),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:s,deviceType:i=Pr(s),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:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' 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:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Pr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Ul=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let d;r?d=r:d=Am({code:e===V.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},o)});super(d);c(this,"name","RtcError");c(this,"code");c(this,"extraCode");c(this,"functionName");c(this,"message");c(this,"handler");c(this,"originError");this.name=Pt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=d,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");pr?m.href=`ms-settings:privacy-${h[this.functionName]}`:Dt&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof b){let{stack:n}=e,a={code:V.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=V.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=V.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=V.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Me.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=V.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=V.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=sT(e.name));break;case S.UNKNOWN:break;default:a.code=V.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
53
|
+
`)))}else{if(e instanceof s)return e;o=new s({code:V.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function sT(s){let i;switch(s){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 w=Ul;var Cm={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}}},Rm={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}}},bs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(K(s)&&!document.getElementById(s))throw new w({code:V.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},ym={name:"userId",required:!0,type:"string"},bm={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[St.AUDIO_PROFILE_STANDARD,St.AUDIO_PROFILE_STANDARD_STEREO,St.AUDIO_PROFILE_HIGH,St.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Wo(s,i){if(!s)throw new w({code:V.INVALID_OPERATION,extraCode:5101,fnName:i})}function Nm(s,i,e){if(!s)throw new w({code:V.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var jD={type:"number",notLessThanZero:!0},oT={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new w({code:V.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(K(s.roomId))throw new w({code:V.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new w({code:V.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new w({code:V.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new w({code:V.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:bs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Cm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&bi())throw new w({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:M(v({},bs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Cm}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:bm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&bi())throw new w({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:bm}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:bs,publish:{type:"boolean"},option:Rm},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(bi())throw new w({code:V.ENV_NOT_SUPPORTED,extraCode:5201});if(!So())throw new w({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:bs,publish:{type:"boolean"},option:Rm}},muteRemoteAudio:[ym,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[ym,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:bs,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(s,i,e){Wo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Nm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new w({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:M(v({},bs),{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(s,i,e){Wo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Nm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new w({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&g(s.streamType))throw new w({code:V.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Wo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!Ro)throw new w({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new w({code:V.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new w({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new w({code:V.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Wo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new w({code:V.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new w({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new w({code:V.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Wo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new w({code:V.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},we={TRTC:oT};var We=class extends Error{};function nT(s,i){let e=lr(s);for(let t=0;t<i.length;t++)Ht(e[t],i[t]);return e}function aT(s){this._resolve=Promise.resolve(s)}function cT(s){this._reject=Promise.reject(s)}var Zi=class Zi{constructor(i,e){this.instance=i;this.group=e;c(this,"started",!1);c(this,"ops",[]);c(this,"startSame",()=>!0);c(this,"mergeUpdate",nT);let t=Zi.instances.get(i);t?t.set(e,this):Zi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Zi.instances.get(i);return t&&t.get(e)||new Zi(i,e)}static gets(i,e){let t=Zi.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},o=a=>{var d,l;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new We("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:aT,reject:cT};try{switch(this.state){case 1:if(i===0)throw new We("already started");break;case 4:if(i===2)throw new We("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new We("already start");break;case 3:switch(i.type){case 2:throw new We("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new We("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new We("keep stop");if(this.ops.slice(1).forEach(r=>r.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 We("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new We("start not allowed after update");case 0:throw new We("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new We("keep start")),new We("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});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}};c(Zi,"instances",new WeakMap);var xi=Zi;var Ha=new WeakMap,Ga=(s,i)=>{if(i instanceof We){let{stack:e}=i;i=new w({code:V.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
54
|
+
`)))}throw i};function er(s,i){return q((e,t)=>function(...r){let o=xi.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(Ga.bind(null,t))):e.apply(this,r)})}function wr(s,i){let{merge:e,debounce:t}=i||{};return q((r,o)=>function(...n){let a=xi.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=t;return new Promise((u,h)=>{var I,R;let m=(I=Ha.get(this))==null?void 0:I.get(l(...n));if(m){let{timeoutId:D,resolve:W}=m;clearTimeout(D),W()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(Ga.bind(null,o)).then(u,h)},d);Ha.has(this)?(R=Ha.get(this))==null||R.set(l(...n),{timeoutId:_,resolve:u}):Ha.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(Ga.bind(null,o))})}function tr(s){return q((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(xi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=xi.get(this,r);return o?o.action(3,i.bind(this),t).catch(Ga.bind(null,e)):i.apply(this,t)})}var k={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},vm=new Set([k.ERROR,k.AUTOPLAY_FAILED,k.KICKED_OUT,k.REMOTE_USER_ENTER,k.REMOTE_USER_EXIT,k.REMOTE_AUDIO_AVAILABLE,k.REMOTE_AUDIO_UNAVAILABLE,k.REMOTE_VIDEO_AVAILABLE,k.REMOTE_VIDEO_UNAVAILABLE,k.CONNECTION_STATE_CHANGED,k.PUBLISH_STATE_CHANGED,k.SCREEN_SHARE_STOPPED,k.DEVICE_CHANGED,k.FIRST_VIDEO_FRAME]);function ir(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function Jo(s){return s===St.QOS_PREFERENCE_CLEAR?"detail":s===St.QOS_PREFERENCE_SMOOTH?"motion":""}var Bl={};ui(Bl,{bytes2ms:()=>Fu,convertObjectNumberToInt:()=>Zs,copyProperties:()=>Bu,deepClone:()=>lr,deepMerge:()=>Ht,delay:()=>gi,fibonacci:()=>hr,formatedTime:()=>Xu,getConstructorName:()=>Ys,getContainerFromElement:()=>qu,getEnv:()=>Uu,getInternalVersion:()=>Ju,getLoggerUrl:()=>fi,getMediaStreamTrackInfo:()=>bn,getMuteStateFromFlag:()=>_i,getNetworkType:()=>xc,getNumNetworkType:()=>ur,getReconnectionTimeout:()=>yt,getStringByteLength:()=>Ks,getTurnServer:()=>ju,getUint32Version:()=>Cn,getValueType:()=>Re,getViewListFromView:()=>zr,glog:()=>Bc,ipv4ToUint32:()=>Xr,isArray:()=>Se,isAudioWorkletSupported:()=>Wu,isBoolean:()=>fe,isConstructor:()=>jr,isEmpty:()=>qr,isFunction:()=>ae,isLangChinese:()=>Rt,isMediaStreamTrack:()=>Hu,isNumber:()=>Q,isObject:()=>$t,isOverseaSdkAppId:()=>Qs,isPlainObject:()=>tt,isPortrait:()=>An,isPromise:()=>Wi,isRemoteTrack:()=>Gu,isString:()=>K,isUndefined:()=>g,loadImage:()=>Qr,ms2bytes:()=>$u,ms2samples:()=>Vc,normalizeUrl:()=>yn,performanceNow:()=>L,promiseAny:()=>mr,samples2ms:()=>Uc,setNetworkType:()=>Sn,stringify:()=>_t,stringifyIncludeValue:()=>In,throttlePromise:()=>Rn});var Hl={};ui(Hl,{ScheduleRequestType:()=>Om,getAbilityConfig:()=>lT,getScheduleDomain:()=>km,isNeedToSchedule:()=>Wa,scheduleProxy:()=>sr,sendScheduleRequest:()=>$l,setIsNeedToSchedule:()=>wt,setScheduleProxy:()=>Ja});var Fl=null,Wa=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(pi).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
55
|
+
`));function wt(s){fe(s)&&s!==Wa&&(Wa=s,C.info(`setIsNeedToSchedule ${s}`))}E.on("28",()=>wt(!0));E.on("63",()=>wt(!0));E.on("84",()=>wt(!0));E.on("201",s=>{s.state==="RECONNECTING"&&wt(!0)});E.on("202",s=>{s.state==="RECONNECTING"&&wt(!0)});function dT(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=rr(s,"config",p.MAIN),n=rr(s,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let d=a.name===o?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),I=Math.round(a.requestStart-a.secureConnectionStart),R=Math.round(a.secureConnectionStart-a.connectStart),D=Math.round(a.responseStart-a.requestStart),W=Math.round(a.responseEnd-a.responseStart),te=[_,I,R,D,W];ee.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${te.join("->")}) ${d}`,userId:i}),t=M(v({},t),{totalCost:l,local:u,dns:_,tcp:R,tls:I,request:D,response:W});break}}catch(r){C.error("getScheduleDetailCost error",r)}return t}function $l(l){return f(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:d}){if(!Wa&&Fl)return{isCached:!0,result:Fl};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(s)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",o),h.append("userSig",String(r)),a&&h.append("role",String(a)),d&&h.append("latencyLevel",String(d)),n&&h.append("frameWorkType",String(n));let m=L(),_=yield hT(h,u,i);_.config&&(_.config.loggerDomain&&or(_.config.loggerDomain),fe(_.config.scheduleCache)&&wt(!_.config.scheduleCache)),u.delta=L()-m;let I=dT(Number(i),s,m);return Fl=_,{isCached:!1,result:_,detailCost:I}}catch(h){let m=Se(h)?h[0]:h,_=Q(m.code)?m.code:0,I=`schedule failed${m.message?`: ${m.message}`:""}`,R=new b({code:S.SCHEDULE_FAILED,extraCode:_,message:U({key:x.JOIN_ROOM_FAILED,data:{error:I,code:_}})});throw C.error(I,_),R}})}var sr={main:"",backup:""};function Ja(s){Se(s)?(sr.main=s[0],sr.backup=s[1]):sr.main=s}var Om=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Om||{});function rr(s,i,e=p.MAIN,t=!1){return`https://${sr[e]||km(s,e,t)}/api/v1/${i}`}function lT(s,i,e){let t=rr(s,i),r=rr(s,i,p.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(d=>d.json()),a=fetch(`${r}?${o}`).then(d=>d.json());return mr([n,a])}function km(s,i=p.MAIN,e=!1){let t;return Qs(s)?e?t=i===p.MAIN?pi.MAIN_OVERSEA_BACKUP:pi.BACKUP_OVERSEA:t=i===p.MAIN?pi.MAIN_OVERSEA:pi.BACKUP_OVERSEA:t=i===p.MAIN?pi.MAIN:pi.BACKUP,t}function uT(s,i,e){return new Promise((t,r)=>{Ti({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var Dm=(s,i)=>Wt({retryFunction:uT,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function hT(s,i,e){return new Promise((t,r)=>{let o=null;mr([Dm(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(d>=1&&(l[0]=rr(e,"config",p.MAIN,!0)),a())})(rr(e,"config",p.MAIN),s,{get timeout(){return hr(2+i.count[0])*1e3}}),Dm(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(d>=2&&(l[0]=rr(e,"config",p.BACKUP,!0)),a())})(rr(e,"config",p.BACKUP),s,{get timeout(){return hr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var mT=s=>s.startsWith("data:application/octet-stream;base64,"),pT=s=>s.startsWith("file://"),ja=class{constructor(){c(this,"_log");this._log=C.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=yn(i);try{let r=L(),o;if(ae(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=L()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),N.addSuccessEvent({key:522700,cost:L()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),N.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):r(new Error("XHR failed"))},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=L(),r=null,o=null;if(ae(WebAssembly.instantiateStreaming)&&!mT(i)&&!pT(i)&&ae(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=L()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),N.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),N.addFailedEvent({key:522701,error:o}),o})}};y([rt({settings:{timeout:0,retries:3},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],ja.prototype,"download",1);var Mm=new ja;function Lm({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:Mm,innerEmitter:E,constants:wc,environment:cs,utils:Bl,eventLogger:ee,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:N,rtcDectection:Yt,trtc:this,rx:Pl,enums:Td,schedule:Hl,clearStarted:(r,o)=>{let n=r.getAlias(),a=xi.instances.get(this);if(a)if(o){let d=a.get(n+o);if(!d)return;d.started=!1}else a.forEach((d,l)=>{l.startsWith(n)&&(d.started=!1)})},startGetPCM:xo,createAudioNode:Wd}}var Pm=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=U({key:x.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
|
|
56
56
|
|
|
57
|
-
${r.stack}`),!1}},s};var Ds=new WeakMap;function Bm(s){let i=Ds.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ds.delete(s))}function Fm(s,i){return z((e,t)=>function(...r){let o=Ds.get(this);o||(o=new Map,Ds.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ds.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ds.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var Hm="trtc-sdk-v5",Gm="5.10.2-beta.5";function Xe(...s){return z((i,e)=>function(...t){try{Qa.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function jl(...s){return z((i,e)=>function(...t){try{Qa.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function Qa(s,i,e,t){if(_e(s))for(let r=0;r<s.length;r++)za.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else za.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function za({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(E(i)){if(s.required)throw new B(o(5001));if(E(s.defaultValue)){se(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),se(s.type[l])&&i instanceof s.type[l]&&(c=!0),K(s.type[l])&&Ee(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new B({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>fr(l)?Xr(l):K(l)?l:Ee(l))},value:i}})}else if(!E(s.type)&&Ee(i)!==s.type)throw new B(o(5002));if(s.allowEmpty===!1){let c=Q(i)&&(i===0||Number.isNaN(i)),l=K(i)&&i.trim()==="";if(c||l)throw new B(o(5003))}if(s.notLessThanZero&&Q(i)&&i<0)throw new B(o(5006));if(!E(s.min)&&Q(i)&&i<s.min)throw new B(o(5007));if(!E(s.max)&&Q(i)&&i>s.max)throw new B(o(5008));if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new B(o(5004))}else if(se(s.instanceOf)&&!(i instanceof s.instanceOf))throw new B(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new B(o(5005));let{properties:n}=s;He(n)&&bt(i)&&Object.keys(n).forEach(c=>{za.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;He(a)&&_e(i)&&i.forEach((c,l)=>{za.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),se(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return z((o,n)=>function(...a){var u;function c(f,g,D){if(D&&D.includes(f))return"hided";if(e){let _=e(...a);if(a[_.argIndex]===g)return _.value}if(g===a||f in a)return g;try{return g instanceof HTMLElement?`id: ${g.id} type:${Ee(g)}`:g instanceof MediaStreamTrack?Nn(g):(JSON.stringify(g),g)}catch(_){return`type:${Ee(g)}`}}let l=this._log||R;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(f,g)=>c(f,g,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let h=t?t(...a):ea[n];try{let f=o.apply(this,a),g=x();return qi(f)?f.then(D=>(l.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:h,cost:x()-g}),D)).catch(D=>{var M;D=B.convertFrom.call(this,D,n,a.length===1?a[0]:a);let _=D.extraCode||D.code,C=(M=D.message)!=null&&M.includes(_)?"":` code:${_}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${D}${C} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:D}),D}):(N.addSuccessEvent({key:h}),f)}catch(f){f=B.convertFrom.call(this,f,n);let g=f.extraCode||f.code,D=(u=f.message)!=null&&u.includes(g)?"":` code:${g}`;throw l.error(`${n}() failed ${f}${D} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:f}),f}})}var Ya=s=>z((i,e)=>function(t,r){return p(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new B({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(se(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new B({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Qa.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Ka=0,ql=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Ts(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()}updateSettings(i){this.player&&(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}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)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Os(s,i){if(i&&typeof i!="function")throw new B({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var hi=class hi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Ka=Ka+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ka}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ka}`),this.core=i}getName(){return hi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return hi.startValidateRule;case"update":return hi.updateValidateRule;case"stop":return hi.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:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new ql(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),N.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),E(t)||n.setOperation(t),E(r)||n.seek(r),this.kvUpload(i)})}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()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:h}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),o&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof c!="function"&&N.addCount({key:502709}),typeof h!="function"&&N.addCount({key:502710}),typeof l!="function"&&N.addCount({key:502708})}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()}};d(hi,"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 r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new B({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new B({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Os("onTimeUpdate",i.onTimeUpdate),Os("onEnded",i.onEnded),Os("onDurationChange",i.onDurationChange)}}),d(hi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Os("onTimeUpdate",i.onTimeUpdate),Os("onEnded",i.onEnded),Os("onDurationChange",i.onDurationChange)}}),d(hi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(hi,"Name","AudioMixer");var Za=hi;var ec=0,Xl,Fi=class Fi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Re("denoiser"));d(this,"workletNode");ec=ec+1,this.log=i.log.createChild({id:`${this.getAlias()}${ec}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${ec}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(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,r,o){if(!i.room.audioManager.hasAudioTrack)throw new B({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Xl||(Xl=this.doPreload(i)),Xl}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield yr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Fi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Fi.startValidateRule(this.core);case"update":return Fi.updateValidateRule;case"stop":return Fi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield RT(t,w(v({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${c}`),new B({code:$.INVALID_PARAMETER,message:c});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:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var u;let{data:h}=l;if(h.type==="cost"){let f=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[f](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${ln(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(u=h==null?void 0:h.hist)==null?void 0:u.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.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(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Fi,"updateValidateRule",{type:"object"}),d(Fi,"stopValidateRule",{type:"object"}),d(Fi,"Name","AIDenoiser");var tc=Fi;function RT(o,n){return p(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:h}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:c};let u="Init RTCAIDenoiser failed.",f="";switch(a){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:h,message:c?`${u} Reason: ${c}. ${f}`:`${u}, ${f}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wm=Be(Qe(),1);var zl=class extends Wm.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!he&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){te.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){te.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},CT=new zl,Ql=CT;function Yl([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Pi(new DataView(new Uint8Array(o).buffer),!0)}function Kl(s){return s.type==="empty"||s.data.byteLength===0}function Zl(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function eu(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function tu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-eu(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Yl),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,c.getInt8(h));return s.data=n,s}function iu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Kl(s)||!Zl(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Pi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var ru=0,Xo=class Xo{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);ru++,this.log=i.log.createChild({id:`${this.getAlias()}${ru}`}),this.log.info(`[sei] created id=${this.getAlias()}${ru}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return tu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return iu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Oi?this.encode:tu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Oi?this.decode:iu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xo.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xo,"autoStart",!0),d(Xo,"Name","SEI");var ic=Xo;function su({frame:s,onDump:i}){return i==null||i(),s}function ou({frame:s,onDump:i}){return i==null||i(),s}var Jm={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
57
|
+
${r.stack}`),!1}},s};var Ns=new WeakMap;function wm(s){let i=Ns.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ns.delete(s))}function xm(s,i){return q((e,t)=>function(...r){let o=Ns.get(this);o||(o=new Map,Ns.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=Ns.get(this))==null||l.delete(n)},s);o.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ns.get(this))==null||l.delete(n)},s);o.set(n,d)}})}var Vm="trtc-sdk-v5",Bm="5.10.2-beta.6";function Je(...s){return q((i,e)=>function(...t){try{Xa.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Gl(...s){return q((i,e)=>function(...t){try{Xa.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function Xa(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)qa.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else qa.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function qa({rule:s,value:i,key:e,fnName:t,className:r}){function o(d){return{code:V.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(g(i)){if(s.required)throw new w(o(5001));if(g(s.defaultValue)){ae(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let d=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(d=!0),ae(s.type[l])&&i instanceof s.type[l]&&(d=!0),K(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(d=!0);if(!d)throw new w({code:V.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>jr(l)?Ys(l):K(l)?l:Re(l))},value:i}})}else if(!g(s.type)&&Re(i)!==s.type)throw new w(o(5002));if(s.allowEmpty===!1){let d=Q(i)&&(i===0||Number.isNaN(i)),l=K(i)&&i.trim()==="";if(d||l)throw new w(o(5003))}if(s.notLessThanZero&&Q(i)&&i<0)throw new w(o(5006));if(!g(s.min)&&Q(i)&&i<s.min)throw new w(o(5007));if(!g(s.max)&&Q(i)&&i>s.max)throw new w(o(5008));if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new w(o(5004))}else if(ae(s.instanceOf)&&!(i instanceof s.instanceOf))throw new w(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new w(o(5005));let{properties:n}=s;tt(n)&&$t(i)&&Object.keys(n).forEach(d=>{qa.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=s;tt(a)&&Se(i)&&i.forEach((d,l)=>{qa.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),ae(s.validate)&&s.validate.call(this,i,e,t,r,this)}function pe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return q((o,n)=>function(...a){var h;function d(m,_,I){if(I&&I.includes(m))return"hided";if(e){let R=e(...a);if(a[R.argIndex]===_)return R.value}if(_===a||m in a)return _;try{return _ instanceof HTMLElement?`id: ${_.id} type:${Re(_)}`:_ instanceof MediaStreamTrack?bn(_):(JSON.stringify(_),_)}catch(R){return`type:${Re(_)}`}}let l=this._log||C;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(m,_)=>d(m,_,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let u=t?t(...a):Zn[n];try{let m=o.apply(this,a),_=L();return Wi(m)?m.then(I=>(l.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:u,cost:L()-_}),I)).catch(I=>{var W;I=w.convertFrom.call(this,I,n,a.length===1?a[0]:a);let R=I.extraCode||I.code,D=(W=I.message)!=null&&W.includes(R)?"":` code:${R}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${I}${D} params: ${JSON.stringify(a,d)}`),N.addFailedEvent({key:u,error:I}),I}):(N.addSuccessEvent({key:u}),m)}catch(m){m=w.convertFrom.call(this,m,n);let _=m.extraCode||m.code,I=(h=m.message)!=null&&h.includes(_)?"":` code:${_}`;throw l.error(`${n}() failed ${m}${I} params: ${JSON.stringify(a,d)}`),N.addFailedEvent({key:u,error:m}),m}})}var za=s=>q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new w({code:V.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ae(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new w({code:V.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Xa.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Qa=0,Wl=class{constructor(i,e){c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new _s(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()}updateSettings(i){this.player&&(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}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)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function vs(s,i){if(i&&typeof i!="function")throw new w({code:V.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ci=class ci{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);Qa=Qa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Qa}`),this.core=i}getName(){return ci.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ci.startValidateRule;case"update":return ci.updateValidateRule;case"stop":return ci.stopValidateRule}}start(i){return f(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:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Wl(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),N.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),g(t)||n.setOperation(t),g(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(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()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:u}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),o&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof d!="function"&&N.addCount({key:502709}),typeof u!="function"&&N.addCount({key:502710}),typeof l!="function"&&N.addCount({key:502708})}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()}};c(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 r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new w({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new w({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),c(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"]}},validate(i,e,t){vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),c(ci,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(ci,"Name","AudioMixer");var Ya=ci;var Ka=0,Jl,Ui=class Ui{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",Le("denoiser"));c(this,"workletNode");Ka=Ka+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ka}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ka}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(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,r,o){if(!i.room.audioManager.hasAudioTrack)throw new w({code:V.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Jl||(Jl=this.doPreload(i)),Jl}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Cr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Ui.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Ui.startValidateRule(this.core);case"update":return Ui.updateValidateRule;case"stop":return Ui.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:d}=yield fT(t,M(v({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${d}`),new w({code:V.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var h;let{data:u}=l;if(u.type==="cost"){let m=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[m](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${dn(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(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(){this.workletNode&&(this.workletNode.port.onmessage=null)}};c(Ui,"updateValidateRule",{type:"object"}),c(Ui,"stopValidateRule",{type:"object"}),c(Ui,"Name","AIDenoiser");var Za=Ui;function fT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:d};let h="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:m="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:m="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${h} Reason: ${d}. ${m}`:`${h}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Fm=Ue(qe(),1);var jl=class extends Fm.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ue&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){ee.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){ee.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},_T=new jl,ql=_T;function Xl([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new ki(new DataView(new Uint8Array(o).buffer),!0)}function zl(s){return s.type==="empty"||s.data.byteLength===0}function Ql(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function Yl(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Kl({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-Yl(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Xl),o=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),d=new DataView(s.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<s.data.byteLength;u++)a.setInt8(l++,d.getInt8(u));return s.data=n,s}function Zl({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(zl(s)||!Ql(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new ki(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var eu=0,jo=class jo{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);eu++,this.log=i.log.createChild({id:`${this.getAlias()}${eu}`}),this.log.info(`[sei] created id=${this.getAlias()}${eu}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Kl({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Zl({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ni?this.encode:Kl,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ni?this.decode:Zl,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return jo.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(jo,"autoStart",!0),c(jo,"Name","SEI");var ec=jo;function tu({frame:s,onDump:i}){return i==null||i(),s}function iu({frame:s,onDump:i}){return i==null||i(),s}var $m={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
58
58
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
59
59
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
60
60
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
61
|
-
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(s=>{Jm[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var Ek=Object.keys(Jm);var yT=0,rc,Ms=class Ms{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++yT}`}),this.log.info("created")}getName(){return Ms.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return p(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return p(this,null,function*(){var i;try{if(rc)yield rc;else{let e=Date.now(),t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Hm}@${Me}/assets/debug-dialog.js`;rc=this.loadScript(t),yield rc,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):su,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):ou,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return su({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return ou({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};d(Ms,"Name","Debug"),d(Ms,"autoStart",!0),b([ot({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Ms.prototype,"loadScript",1);var sc=Ms;var jm=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},oc=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=ue(e,H.INIT),this.stopOB=et(),this.startOB=et(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=et(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),de(l,xe(this.stopOB),Ce(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:jm(this.type),error:h}),c>4?this.startOB.error(h):this.startOB.next(c+1)})),de(l,Ui(1),Ll(Ho))};de(this.startOB,Fo(0),As(a),xe(this.stopOB),Ce(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:jm(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return xi()(e=>p(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},bT={type:"object"},zo=class zo{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return zo.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return zo.Name}getValidateRule(i){return bT}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new oc(this.core,t,i);return de(r.trackDoneOB,Ui(1),Ce(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new oc(this.core,i.track,i))}}};d(zo,"Name","TRTCAudioDecoder");var Qo=zo;var nc=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return p(this,null,function*(){return se(this[i])?this[i](e):Promise.reject(new y({code:S.INVALID_PARAMETER,message:P({key:L.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return p(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:h}=c;if(h.set(r,{enable:t,sampleRate:o,channelCount:n}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(u=>{if(u.remoteAudioTrack.isAvailable){if(l.get(u.userId))return;let f=c.getPCM(g=>{e.emit(k.AUDIO_FRAME,g)},u.userId);l.set(u.userId,f)}});else{if(l.get(r))return;let u=c.getPCM(f=>{e.emit(k.AUDIO_FRAME,f)},r);l.set(r,u)}else if(r==="*")e.room.remotePublishedUserMap.forEach(u=>{if(u.remoteAudioTrack.isSubscribed){let{userId:f}=u,g=l.get(f);g==null||g.abort("disable"),l.delete(f)}});else{let u=l.get(r);u==null||u.abort("disable"),l.delete(r)}})}};b([Im({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],nc.prototype,"enableAudioFrameEvent",1);var qm=new nc;var Xm=0,Yo=new Set,Ve=null;bc(Gm);us.checkStorage();Pd();var NT={RtcError:B,ErrorCode:$,ErrorCodeDictionary:Ut},q=class q extends zm.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++Xm}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");this._room=new e(v({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Za,t.assetsPath),this._use(tc,t.assetsPath),this._use(Qo,t.assetsPath||un),this._use(sc),t.enableSEI&&bo&&this._use(ic),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(k.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new B({code:$.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Vm(this,"trtc")}static create(e){}static _create(e,t){Cm();let r=new q(e,t||{});return Yo.add(r),r}get room(){return this._room}_listenEvents(){Ge(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(k.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(k.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(k.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(k.ERROR,B.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(k.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=w(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,Ys),downlinkRTT:Math.min(e.downlinkRTT,Ys)});this.emit(k.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ge(r,r).add("player-state-changed",o=>{let n=w(v({},o),{userId:e.userId});r.kind===m.VIDEO&&(n.streamType=or(r.streamType)),this.emit(r.kind===m.AUDIO?k.AUDIO_PLAY_STATE_CHANGED:k.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(k.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{be(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?k.REMOTE_VIDEO_AVAILABLE:k.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?k.REMOTE_AUDIO_AVAILABLE:k.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?k.REMOTE_VIDEO_AVAILABLE:k.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(k.SEI_MESSAGE,w(v({},e),{streamType:or(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(k.ERROR,new B({code:$.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,l,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Ys),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/Et},video:e.msg_up_stream_info.msg_video_status.filter(f=>t[f.uint32_video_stream_type]).map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_enc_fps,videoType:t[f.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(f=>({userId:f.msg_user_info.str_identifier,audio:{bitrate:(f.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(f.msg_audio_status.uint32_audio_level||0)/Et,point2pointDelay:(f.msg_audio_status.uint32_audio_p2p_delay||0)+(f.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:f.msg_audio_status.uint32_audio_cache_ms||0},video:f.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],point2pointDelay:(g.uint32_video_p2p_delay||0)+(g.uint32_video_cache_ms||0),jitterBufferDelay:g.uint32_video_cache_ms||0}))}))};this.emit(k.STATISTICS,r)}).add("custom-message",e=>{this.emit(k.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(k.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(k.FIRST_VIDEO_FRAME,w(v({},e),{streamType:or(e.streamType)}))}).add("audio-frame",e=>{this.emit(k.AUDIO_FRAME,e)}),Ge(this,ke).add("audioInputAdded",e=>{this.emit(k.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(k.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ve&&Ve.deviceId===Qs){let t=(yield er()).find(r=>r.deviceId===Qs);t&&Ve.groupId!==t.groupId&&(Ve=t,this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield er())[0];if(!t||!Ve||Ve.groupId===t.groupId)return;let r=Ve.deviceId===e.deviceId,o=Ve.deviceId===Qs&&Ve.deviceId===t.deviceId;(r||o)&&(Ve=t,this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||un)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Um.call(this,{TRTC:q,room:this._room,errorModule:NT,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return p(this,null,function*(){var c,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!K(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,ge(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),Ql.start()})}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),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){be(this),this.removeAllListeners(),this._room.destroy(),Yo.delete(this),Yo.size===0&&Ql.destroy(),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)}),this._plugins.clear(),T.off("102",this._onLocalTrackCaptured,this)}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:r,option:o}=e,n=new St(this._room.audioManager),a={},c={muted:!0};o&&(E(o.microphoneId)?E(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&Q(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),E(o.profile)||(K(o.profile)?pn[o.profile]&&n.setProfile(pn[o.profile]):n.setProfile(o.profile)),Q(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),E(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),E(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),E(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(k.ERROR,new B({code:$.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(k.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=B.convertFrom(l.error)),this.emit(k.PUBLISH_STATE_CHANGED,w(v({},l),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),E(r)||n.setMute(r),Ge(n,n).add("player-state-changed",l=>{this.emit(k.AUDIO_PLAY_STATE_CHANGED,w(v({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),T.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):E(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),E(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),E(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),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(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,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(()=>{})),T.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),be(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:r=!0,mute:o,option:n}=e,a=new Je(this._room.videoManager),c={},l={};ge(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?c.deviceId=n.cameraId:E(n.useFrontCamera)?E(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,n.qosPreference&&(c.contentHint=qo(n.qosPreference)),E(n.profile)||(K(n.profile)?gt[n.profile]&&a.setProfile(gt[n.profile]):a.setProfile(n.profile)),E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror),E(n.small)||(Ro()?K(n.small)?a.small=gt[n.small]:n.small===!0?a.small=gt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",h=>{this.emit(k.FIRST_VIDEO_FRAME,w(v({},h),{streamType:or(h.streamType)}))}),a.on("5",h=>{this.emit(k.ERROR,new B({code:$.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=B.convertFrom(h.error)),this.emit(k.PUBLISH_STATE_CHANGED,w(v({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(o)||(yield a.setMute(o)),Ge(a,a).add("player-state-changed",h=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,w(v({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=w(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(E(n.profile)||(K(n.profile)?gt[n.profile]&&this._localVideoTrack.setProfile(gt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&E(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):E(n.useFrontCamera)?E(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),E(n.fillMode)||(a.objectFit=n.fillMode),E(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(qo(n.qosPreference)),n.small){let c=!this._localVideoTrack.small;Ro()?(n.small===!0?this._localVideoTrack.small=gt["120p"]:K(n.small)?this._localVideoTrack.small=gt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!E(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(o)||(yield this._localVideoTrack.setMute(o)),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(),be(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:r=!0,option:o}=e,n=new ct(this._room.videoManager);n.on("4",u=>{let f;u.error&&(f=B.convertFrom(u.error)),this.emit(k.PUBLISH_STATE_CHANGED,w(v({},u),{error:f}))}),n.once("first-video-frame",u=>{this.emit(k.FIRST_VIDEO_FRAME,w(v({},u),{streamType:or(u.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},l={};o&&(E(o.profile)||(K(o.profile)?fn[o.profile]&&n.setProfile(fn[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),E(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(c.contentHint=qo(o.qosPreference)));let h=yield n.capture(c);if(n.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(k.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new ci(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Ge(n,n).add("player-state-changed",u=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,w(v({},u),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let u=[n];a&&u.push(a),this._room.publish(...u).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=w(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(E(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=qo(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!E(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,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:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},h=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror),E(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!E(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var C,M;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u!=null&&u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:f}=c;o==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:h,prevConfig:f}),Wt(f,e);let g=E(n==null?void 0:n.receiveWhenViewVisible)?(C=f.option)==null?void 0:C.receiveWhenViewVisible:n.receiveWhenViewVisible,D=E(t)?f.view:t,_=E(n==null?void 0:n.viewRoot)?(M=f.option)==null?void 0:M.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:D,receiveWhenViewVisible:g,viewRoot:_})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return p(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.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,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(k.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:o}=this.room.audioManager;o.get("")||o.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{km.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:o}=this.room.audioManager;o.forEach(n=>{n==null||n.abort("off")}),o.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(K(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return p(this,null,function*(){(yield er()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Ve=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),c=Q(a)?a:100;o.volume=c,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),de(ue(n,"decode-failed"),xe(ue(n,H.INIT)),Ce(()=>{this.startPlugin(Qo.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),T.emit("115",{userId:t,room:this.room})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),T.emit("116",{userId:e.userId,room:this.room})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;de(ue(e,"decode-failed"),xe(ue(e,H.INIT)),xl(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Lr(ue(e,"decode-downgrade-state-changed")),Ce(n=>{o=n.state,this.emit(k.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,w(v({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),E(e)&&o&&o.view&&!zr(t)){let a=Yr(o.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=Yr(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}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,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(k.TRACK,{userId:r,streamType:or(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(E(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${or(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||_e(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(f=>{f.forEach(g=>{l.set(g.target,g.isIntersecting),e.log.info(`view ${g.target.id} is${g.isIntersecting?"":" not"} visible`)}),clearTimeout(h),h=window.setTimeout(()=>{[...l.values()].find(D=>D)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(Yr(t));l.forEach((f,g)=>{u.has(g)||(a.unobserve(g),l.delete(g))}),u.forEach(f=>{l.set(f,!0),a.observe(f)}),a.takeRecords().forEach(f=>{l.set(f.target,f.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Bm(this),this._room.remotePublishedUserMap.forEach(e=>{be(e.remoteAudioTrack),be(e.remoteVideoTrack),be(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),be(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ve||Es(Ve))&&(this._initActiveSpeaker(),T.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return p(this,null,function*(){if(Ve&&!Es(Ve))this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ve});else{let e=yield er();e[0]&&!Es(e[0])?(Ve=e[0],this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):T.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).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){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:w(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),N.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),N.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return p(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),qm.call(e,v({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),E(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return sa()}static getCameraList(e=!0){return _t(e)}static getMicrophoneList(e=!0){return nt(e)}static getSpeakerList(e=!0){return er(e)}static setCurrentSpeaker(e){return p(this,null,function*(){if(he&&(e===At.SPEAKER||e===At.HEADSET)){let r=yield q.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;Yo.forEach(n=>p(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield er()).forEach(r=>{r.deviceId===e&&(Yo.forEach(o=>{o._setCurrentSpeaker(e),o.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Ve=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Ar.version=a),e){case"count":Ar.addCount({key:t,useUV:n});break;case"enum":Ar.addEnum({key:t,value:r,useUV:n});break;case"number":Ar.addNumber({key:t,value:r,split:o});break}}};d(q,"_loggerManager",R),d(q,"EVENT",k),d(q,"ERROR_CODE",$),d(q,"TYPE",At),d(q,"frameWorkType",30),b([fe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],q.prototype,"use",1),b([Xe(Ue.TRTC.enterRoom),rr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),z(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),fe()],q.prototype,"enterRoom",1),b([fe()],q.prototype,"exitRoom",1),b([Xe(Ue.TRTC.switchRole),Ur("room",{merge:(e,t)=>t}),fe()],q.prototype,"switchRole",1),b([fe()],q.prototype,"destroy",1),b([Xe(Ue.TRTC.startLocalAudio),rr("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),fe()],q.prototype,"startLocalAudio",1),b([Xe(Ue.TRTC.updateLocalAudio),Ur("audio",{debounce:{delay:200,getKey:()=>`${Xm}-localAudio`,isNeedToDebounce:e=>{var t;return!E((t=e.option)==null?void 0:t.captureVolume)}}}),fe()],q.prototype,"updateLocalAudio",1),b([sr("audio"),fe()],q.prototype,"stopLocalAudio",1),b([Xe(Ue.TRTC.startLocalVideo),rr("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),fe()],q.prototype,"startLocalVideo",1),b([Xe(Ue.TRTC.updateLocalVideo),Ur("video"),fe()],q.prototype,"updateLocalVideo",1),b([sr("video"),fe()],q.prototype,"stopLocalVideo",1),b([Xe(Ue.TRTC.startScreenShare),rr("screen",()=>!0),fe()],q.prototype,"startScreenShare",1),b([Xe(Ue.TRTC.updateScreenShare),Ur("screen"),fe()],q.prototype,"updateScreenShare",1),b([fe()],q.prototype,"stopScreenShare",1),b([Xe(Ue.TRTC.startRemoteVideo),rr(e=>`v${e.userId}${e.streamType}`,()=>!0),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),b([Xe(Ue.TRTC.updateRemoteVideo),Ur(e=>`v${e.userId}${e.streamType}`),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),b([Xe(Ue.TRTC.stopRemoteVideo),z(e=>function(t){return p(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),b([sr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),b([Xe(...Ue.TRTC.muteRemoteAudio),fe({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),b([jl(...Ue.TRTC.setRemoteAudioVolume),Fm(200,e=>e),fe({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),b([Ya("start"),Ze(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),rr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Rd[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],q.prototype,"startPlugin",1),b([Ya("update"),Ur((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Cd[e.getName()]})],q.prototype,"updatePlugin",1),b([Ya("stop"),sr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>yd[e.getName()]})],q.prototype,"stopPlugin",1),b([jl(...Ue.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),b([fe()],q.prototype,"getVideoSnapshot",1),b([fe()],q.prototype,"_setCurrentSpeaker",1),b([rr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),b([z(e=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(w(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),sr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),b([sr("room")],q.prototype,"_exitRoom",1),b([sr("screen")],q.prototype,"_stopScreenShare",1),b([Xe(...Ue.TRTC.sendSEIMessage),Bl({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),b([Xe(Ue.TRTC.sendCustomMessage),Bl({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),b([Xe(Ue.TRTC.create)],q,"_create",1);var nu=q,Ko=nu;var au=class{constructor(){d(this,"_set",new Set);T.on(I.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,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function vT(){return p(this,null,function*(){let s,i;try{let u=yield nt();s=u&&u.length}catch(u){}try{let u=yield _t();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=ti.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:c,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};te.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),te.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function Qm(){return z(s=>{let i=new au;return function(e,t,r){return p(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new y({code:S.INVALID_OPERATION,message:P({key:L.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new y({code:S.INVALID_OPERATION,message:P({key:L.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(I.JOIN_START,{room:this,roomId:o,params:e});let n=dt.getEnv();n||(n=_i.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_n.OLD_CLOUD_LADDER)?n=_i.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_n.WEBRTC)&&(n=_i.WEBRTC))),te.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),ti.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,vT.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!dt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=dt.performanceNow(),T.emit(I.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&te.uploadEvent({log:`stat-conv-${Number(Lt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(I.JOIN_FAILED,{room:this,error:a}),a}})}})}var Ym=()=>z(s=>function(...i){return p(this,null,function*(){T.emit(I.LEAVE_START,{room:this}),yield s.call(this,...i),T.emit(I.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Km(){return z(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var ep=Be(Qe());var ye={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Bt={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,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,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,RECEIVE_CUSTOM_MSG:4140},Zm=[Bt.UPDATE_REMOTE_MUTE_STAT,Bt.UPLINK_NETWORK_STATS,Bt.USER_LIST_RES,Bt.MUTE_RESULT,Bt.SERVER_FIRST_PACKAGE_RECEIVED,Bt.RECEIVE_CUSTOM_MSG],G={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",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-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",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},Y={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",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",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",SEND_CUSTOM_MSG:"channel_msg"};var ac=new Set;function tp(s){let i=[...ac.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var ks=class extends ep.default{constructor(e){var r,o,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-ac.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ac.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.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 race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),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 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}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=x();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 _r(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?m.MAIN:m.BACKUP),c(new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}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===m.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){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.startReconnection(),this.room.isJoining&&this.emit(ye.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(ye.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=eo(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Bt),c=Object.keys(Bt)[n.indexOf(r)],l=G[c]||r;switch(Zm.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Bt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&wu(o.svrTime),this._log.info(`ChannelSetup Success ${x()-this._connectStartTime}`),N.addSuccessEvent({key:521701,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.emit(ye.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:P({key:L.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),N.addFailedEvent({key:521701,error:h}),this.emit(ye.SETUP_FAILED,h)}break}case Bt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{if(!this.room.joinParams)return;Vt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?m.MAIN:m.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}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:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Y.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:G.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(N.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 r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=eo(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,h)=>{let u=setTimeout(()=>{this.off(o,g);let _=new y({code:S.API_CALL_TIMEOUT,message:P({key:L.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(_),h(_)},r),f=Date.now(),g=_=>{_.data.seq===D&&(clearTimeout(u),this.off(o,g),c&&(_.data.receiveTime=Date.now()),l(_))};this.on(o,g);let D=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return jt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(ye.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),ac.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(G.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(G.JOIN_ROOM_RESULT,t))};this.on(G.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(ye.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(ye.CONNECTED):e==="DISCONNECTED"&&this.emit(ye.DISCONNECTED))}};b([ot({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],ks.prototype,"connect",1);var ip=Be(Qe());var cu=0,du=!1,cc=new Set,OT=s=>cu>2&&!du&&cc.size===0&&s,lu=!1,it=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new ip.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=R.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,N.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&N.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={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(),cc.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 y({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return yt;let i=null;if(this._isUplink){if(!Zi()||this._peerConnection.getSenders().length===0)return yt;i=this._peerConnection.getSenders()[0].transport}else{if(!Rr()||this._peerConnection.getReceivers().length===0)return yt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:yt}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===me.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===me.FAILED||i.target.connectionState===me.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new y({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===me.CONNECTED||i.target.connectionState===me.COMPLETED)&&(this.logSelectedCandidate(),te.logSuccessEvent({userId:this._room.userId,eventType:rt.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(cu=0,du=!1,lu=!0,cc.add(this)):cc.delete(this),T.emit(I.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(Ki(e)){let t=i.get(e.localCandidateId),r=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}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(I.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});cu+=1,OT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),du=!0,this._emitter.emit("firewall-restriction")),e(a)},Xs);T.on(I.LEAVE_SUCCESS,r,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(ye.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=gi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new y({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:P({key:this._isUplink?L.UPLINK_RECONNECTION_FAILED:L.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(ye.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"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};b([at(521712,!1)],it.prototype,"setOffer",1),b([at(521713,!1)],it.prototype,"setAnswer",1);var pu=Be(mu());var Ae=function(s){return pu.default.parse(s)},Rt=function(s){return pu.default.write(s)},lp=function(s){let i=Ae(s);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Rt(i)};function up(s){let i=Ae(s);return i.media.forEach(e=>{var t,r;if(e.type===m.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),Rt(i)}function dc(s){return Object.keys(s).filter(i=>s[i])}var Ps=class Ps extends it{constructor(e){super(w(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new wi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ui(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new bs(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}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 Si(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===qs?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=m.AUDIO;r.kind===m.VIDEO&&(n=o===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;n===m.VIDEO?a=this.remoteVideoTrack:n===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
62
|
-
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,
|
|
63
|
-
`)}addSPSDescription(e){let t=Ae(e);return t.media.forEach(r=>{r.type===m.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),Rt(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"],r=Ae(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),Rt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===me.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===me.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${dc(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:P({key:L.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:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Y.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:G.SUBSCRIBE_RESULT,timeout:xc});if(!this._peerConnection){let a=new y({code:S.INVALID_OPERATION,message:P({key:L.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};mt()&&this._sdpSemantics===ji?(this._peerConnection.addTransceiver(m.AUDIO,{direction:Z.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:Z.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:Z.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield ra();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=up(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=lp(t.sdp),this._sdpSemantics===ji&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===lr)throw new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new y({code:t,message:P({key:L.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ae(e).media.forEach(r=>{if(r.ssrcs)if(r.type===m.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(qs)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(qs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Mc)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return p(this,null,function*(){if(!(Fe(Ps.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=vt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}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}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};b([z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Ps.prototype,"subscribe",1),b([at(521717,!1)],Ps.prototype,"unsubscribe",1),b([Ze(it.prototype.afterConnect),Ea(it.prototype.beforeConnect)],Ps.prototype,"connect",1);var fu=Ps,_u=fu;var mp={voiceActivityDetection:!1},ws=class ws extends it{constructor(e){super(w(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Zt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),mt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let h=this._peerConnection.getTransceivers();if(h.length===0)this._peerConnection.addTransceiver(l||m.AUDIO,{direction:Z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?m.VIDEO:c||m.VIDEO,{direction:Z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||m.VIDEO,{direction:Z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||m.VIDEO:m.VIDEO,{direction:Z.SENDONLY,streams:[a]}),yield this.connect();else{let u=[];if(l&&(h[0].sender.track||u.push(0),yield h[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),c){let f=o?3:1;yield h[f].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:m.VIDEO,videoType:o?m.AUXILIARY:m.BIG}),u.push(f),r&&(yield h[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),u.push(2))}yield this.setTransceiverDirection(Z.SENDONLY,u),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=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)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}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(Z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Z.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(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Zt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},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=w(v({},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(Z.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},r=yield this._signalChannel.sendWaitForResponse({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.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 r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),ei){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.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?m.AUXILIARY:m.MAIN} stream`),mt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Z.INACTIVE&&(yield this.setTransceiverDirection(Z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Zt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===m.VIDEO&&e instanceof Je&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Jr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Ae(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===m.VIDEO)return!0;return!1}removeSender(e){let t=null;Zt()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&se(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?m.AUXILIARY:m.MAIN} stream`),mt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!oe)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
64
|
-
`).map(l=>{if(l.match(new RegExp(`a=(${
|
|
65
|
-
`);o&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:
|
|
66
|
-
`:
|
|
61
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(s=>{$m[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var nM=Object.keys($m);var gT=0,tc,Ds=class Ds{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dumpLocalVideoMap",{});c(this,"dumpRemoteVideoMap",{});c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++gT}`}),this.log.info("created")}getName(){return Ds.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;try{if(tc)yield tc;else{let e=Date.now(),t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Vm}@${ve}/assets/debug-dialog.js`;tc=this.loadScript(t),yield tc,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):tu,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):iu,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return tu({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return iu({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};c(Ds,"Name","Debug"),c(Ds,"autoStart",!0),y([rt({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Ds.prototype,"loadScript",1);var ic=Ds;var Hm=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},rc=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=le(e,B.INIT),this.stopOB=Ye(),this.startOB=Ye(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=Ye(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ce(l,Pe(this.stopOB),Ie(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:Hm(this.type),error:u}),d>4?this.startOB.error(u):this.startOB.next(d+1)})),ce(l,Pi(1),Ol(Fo))};ce(this.startOB,Vo(0),Ss(a),Pe(this.stopOB),Ie(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Hm(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return Li()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},TT={type:"object"},qo=class qo{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return qo.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return qo.Name}getValidateRule(i){return TT}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new rc(this.core,t,i);return ce(r.trackDoneOB,Pi(1),Ie(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new rc(this.core,i.track,i))}}};c(qo,"Name","TRTCAudioDecoder");var Xo=qo;var Gm=0,zo=new Set,xe=null;Cc(Bm);ds.checkStorage();kd();var ET={RtcError:w,ErrorCode:V,ErrorCodeDictionary:Pt},H=class H extends Wm.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",C.createLogger({id:`t${++Gm}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"_getPCMAbortCtrl");this._room=new e(v({logger:this._log,frameWorkType:H.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Ya,t.assetsPath),this._use(Za,t.assetsPath),this._use(Xo,t.assetsPath||ln),this._use(ic),t.enableSEI&&Ro&&this._use(ec),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(k.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new w({code:V.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Pm(this,"trtc")}static create(e){}static _create(e,t){Sm();let r=new H(e,t||{});return zo.add(r),r}get room(){return this._room}_listenEvents(){Fe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(k.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(k.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(k.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(k.ERROR,w.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(k.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=M(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,Xs),downlinkRTT:Math.min(e.downlinkRTT,Xs)});this.emit(k.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Fe(r,r).add("player-state-changed",o=>{let n=M(v({},o),{userId:e.userId});r.kind===p.VIDEO&&(n.streamType=ir(r.streamType)),this.emit(r.kind===p.AUDIO?k.AUDIO_PLAY_STATE_CHANGED:k.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(k.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ce(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?k.REMOTE_VIDEO_AVAILABLE:k.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?k.REMOTE_AUDIO_AVAILABLE:k.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?k.REMOTE_VIDEO_AVAILABLE:k.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(k.SEI_MESSAGE,M(v({},e),{streamType:ir(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(k.ERROR,new w({code:V.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,d,l,u,h;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Xs),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/gt},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/gt},video:m.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(k.STATISTICS,r)}).add("custom-message",e=>{this.emit(k.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(k.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(k.FIRST_VIDEO_FRAME,M(v({},e),{streamType:ir(e.streamType)}))}),Fe(this,De).add("audioInputAdded",e=>{this.emit(k.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(k.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),xe&&xe.deviceId===qs){let t=(yield Yi()).find(r=>r.deviceId===qs);t&&xe.groupId!==t.groupId&&(xe=t,this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Yi())[0];if(!t||!xe||xe.groupId===t.groupId)return;let r=xe.deviceId===e.deviceId,o=xe.deviceId===qs&&xe.deviceId===t.deviceId;(r||o)&&(xe=t,this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||ln)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Lm.call(this,{TRTC:H,room:this._room,errorModule:ET,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return f(this,null,function*(){var d,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!K(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,fe(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,H.frameWorkType),this._checkTrackToPublish(),ql.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Ce(this),this.removeAllListeners(),this._room.destroy(),zo.delete(this),zo.size===0&&ql.destroy(),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)}),this._plugins.clear(),E.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new Tt(this._room.audioManager),a={},d={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&Q(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(K(o.profile)?mn[o.profile]&&n.setProfile(mn[o.profile]):n.setProfile(o.profile)),Q(o.earMonitorVolume)&&(d.muted=!(o.earMonitorVolume>0),d.volume=o.earMonitorVolume),g(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),g(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),g(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(k.ERROR,new w({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(k.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=w.convertFrom(l.error)),this.emit(k.PUBLISH_STATE_CHANGED,M(v({},l),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(r)||n.setMute(r),Fe(n,n).add("player-state-changed",l=>{this.emit(k.AUDIO_PLAY_STATE_CHANGED,M(v({},l),{userId:""}))}),this.listeners(k.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(H.EVENT.AUDIO_FRAME,{data:l})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(H.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=M(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):g(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),g(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),g(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ht(this._localAudioConfig,e)})}stopLocalAudio(){return f(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),Ce(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new He(this._room.videoManager),d={},l={};fe(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?d.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(d.customSource=n.videoTrack):d.facingMode=n.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,n.qosPreference&&(d.contentHint=Jo(n.qosPreference)),g(n.profile)||(K(n.profile)?ft[n.profile]&&a.setProfile(ft[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror),g(n.small)||(Io()?K(n.small)?a.small=ft[n.small]:n.small===!0?a.small=ft["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",u=>{this.emit(k.FIRST_VIDEO_FRAME,M(v({},u),{streamType:ir(u.streamType)}))}),a.on("5",u=>{this.emit(k.ERROR,new w({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let h;u.error&&(h=w.convertFrom(u.error)),this.emit(k.PUBLISH_STATE_CHANGED,M(v({},u),{error:h}))}),this._listenOutputTrackChanged(a),yield a.capture(d),g(o)||(yield a.setMute(o)),Fe(a,a).add("player-state-changed",u=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,M(v({},u),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=M(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(g(n.profile)||(K(n.profile)?ft[n.profile]&&this._localVideoTrack.setProfile(ft[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):g(n.useFrontCamera)?g(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Jo(n.qosPreference)),n.small){let d=!this._localVideoTrack.small;Io()?(n.small===!0?this._localVideoTrack.small=ft["120p"]:K(n.small)?this._localVideoTrack.small=ft[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),d&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!g(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ht(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Ce(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(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:r=!0,option:o}=e,n=new nt(this._room.videoManager);n.on("4",h=>{let m;h.error&&(m=w.convertFrom(h.error)),this.emit(k.PUBLISH_STATE_CHANGED,M(v({},h),{error:m}))}),n.once("first-video-frame",h=>{this.emit(k.FIRST_VIDEO_FRAME,M(v({},h),{streamType:ir(h.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,d={},l={};o&&(g(o.profile)||(K(o.profile)?pn[o.profile]&&n.setProfile(pn[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(d.systemAudio=!0,d.echoCancellation=o.echoCancellation,d.noiseSuppression=o.noiseSuppression,d.autoGainControl=o.autoGainControl),g(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(d.videoTrack=o.videoTrack),o.audioTrack&&(d.audioTrack=o.audioTrack),o.captureElement&&(d.captureElement=o.captureElement),o.preferDisplaySurface&&(d.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(d.contentHint=Jo(o.qosPreference)));let u=yield n.capture(d);if(n.mediaTrack.addEventListener(p.ENDED,()=>{this._stopScreenShare(),this.emit(k.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new si(this._room.audioManager),yield a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Fe(n,n).add("player-state-changed",h=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,M(v({},h),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let h=[n];a&&h.push(a),this._room.publish(...h).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=M(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=Jo(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!g(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Ht(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},u=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror),g(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!g(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,W;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,d=this._remoteVideoConfigMap.get(a);if(!d||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror));let u=null,h=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(h!=null&&h.muteState.hasVideo)&&(u=h.remoteVideoTrack),o==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:m}=d;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:u,prevConfig:m}),Ht(m,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(D=m.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,I=g(t)?m.view:t,R=g(n==null?void 0:n.viewRoot)?(W=m.option)==null?void 0:W.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:I,receiveWhenViewVisible:_,viewRoot:R})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===H.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(H.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(H.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{vm.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===H.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(K(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Yi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),xe=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),d=Q(a)?a:100;o.volume=d,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),ce(le(n,"decode-failed"),Pe(le(n,B.INIT)),Ie(()=>{this.startPlugin(Xo.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;ce(le(e,"decode-failed"),Pe(le(e,B.INIT)),Ll(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),kr(le(e,"decode-downgrade-state-changed")),Ie(n=>{o=n.state,this.emit(k.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,M(v({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),g(e)&&o&&o.view&&!qr(t)){let a=zr(o.view);a.length>0&&(yield r.play(a,t))}if(!g(e)){let a=zr(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}g(e.muted)||t.setPlayerMute(e.muted),g(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,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(k.TRACK,{userId:r,streamType:ir(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${ir(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Se(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let h=new Set(zr(t));l.forEach((m,_)=>{h.has(_)||(a.unobserve(_),l.delete(_))}),h.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),wm(this),this._room.remotePublishedUserMap.forEach(e=>{Ce(e.remoteAudioTrack),Ce(e.remoteVideoTrack),Ce(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(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),Ce(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!xe||gs(xe))&&(this._initActiveSpeaker(),E.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(xe&&!gs(xe))this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:xe});else{let e=yield Yi();e[0]&&!gs(e[0])?(xe=e[0],this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):E.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).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){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:M(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),N.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),N.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){C.setLogLevel(e),g(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return ra()}static getCameraList(e=!0){return pt(e)}static getMicrophoneList(e=!0){return st(e)}static getSpeakerList(e=!0){return Yi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(ue&&(e===St.SPEAKER||e===St.HEADSET)){let r=yield H.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;zo.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Yi()).forEach(r=>{r.deviceId===e&&(zo.forEach(o=>{o._setCurrentSpeaker(e),o.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),xe=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Sr.version=a),e){case"count":Sr.addCount({key:t,useUV:n});break;case"enum":Sr.addEnum({key:t,value:r,useUV:n});break;case"number":Sr.addNumber({key:t,value:r,split:o});break}}};c(H,"_loggerManager",C),c(H,"EVENT",k),c(H,"ERROR_CODE",V),c(H,"TYPE",St),c(H,"frameWorkType",30),y([pe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],H.prototype,"use",1),y([Je(we.TRTC.enterRoom),er("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),q(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),pe()],H.prototype,"enterRoom",1),y([pe()],H.prototype,"exitRoom",1),y([Je(we.TRTC.switchRole),wr("room",{merge:(e,t)=>t}),pe()],H.prototype,"switchRole",1),y([pe()],H.prototype,"destroy",1),y([Je(we.TRTC.startLocalAudio),er("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),pe()],H.prototype,"startLocalAudio",1),y([Je(we.TRTC.updateLocalAudio),wr("audio",{debounce:{delay:200,getKey:()=>`${Gm}-localAudio`,isNeedToDebounce:e=>{var t;return!g((t=e.option)==null?void 0:t.captureVolume)}}}),pe()],H.prototype,"updateLocalAudio",1),y([tr("audio"),pe()],H.prototype,"stopLocalAudio",1),y([Je(we.TRTC.startLocalVideo),er("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),pe()],H.prototype,"startLocalVideo",1),y([Je(we.TRTC.updateLocalVideo),wr("video"),pe()],H.prototype,"updateLocalVideo",1),y([tr("video"),pe()],H.prototype,"stopLocalVideo",1),y([Je(we.TRTC.startScreenShare),er("screen",()=>!0),pe()],H.prototype,"startScreenShare",1),y([Je(we.TRTC.updateScreenShare),wr("screen"),pe()],H.prototype,"updateScreenShare",1),y([pe()],H.prototype,"stopScreenShare",1),y([Je(we.TRTC.startRemoteVideo),er(e=>`v${e.userId}${e.streamType}`,()=>!0),pe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"startRemoteVideo",1),y([Je(we.TRTC.updateRemoteVideo),wr(e=>`v${e.userId}${e.streamType}`),pe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"updateRemoteVideo",1),y([Je(we.TRTC.stopRemoteVideo),q(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),pe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"stopRemoteVideo",1),y([tr(e=>`v${e.userId}${e.streamType}`)],H.prototype,"_stopRemoteVideo",1),y([Je(...we.TRTC.muteRemoteAudio),pe({getRemoteId:e=>e})],H.prototype,"muteRemoteAudio",1),y([Gl(...we.TRTC.setRemoteAudioVolume),xm(200,e=>e),pe({getRemoteId:e=>e})],H.prototype,"setRemoteAudioVolume",1),y([za("start"),Qe(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),er((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),pe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Sd[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],H.prototype,"startPlugin",1),y([za("update"),wr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),pe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Id[e.getName()]})],H.prototype,"updatePlugin",1),y([za("stop"),tr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),pe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ad[e.getName()]})],H.prototype,"stopPlugin",1),y([Gl(...we.TRTC.enableAudioVolumeEvaluation)],H.prototype,"enableAudioVolumeEvaluation",1),y([pe()],H.prototype,"getVideoSnapshot",1),y([pe()],H.prototype,"_setCurrentSpeaker",1),y([er(e=>`a${e.userId}`,()=>!0)],H.prototype,"_startRemoteAudio",1),y([q(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(M(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),tr(e=>`a${e.userId}`)],H.prototype,"_stopRemoteAudio",1),y([tr("room")],H.prototype,"_exitRoom",1),y([tr("screen")],H.prototype,"_stopScreenShare",1),y([Je(...we.TRTC.sendSEIMessage),xl({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],H.prototype,"sendSEIMessage",1),y([Je(we.TRTC.sendCustomMessage),xl({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],H.prototype,"sendCustomMessage",1),y([Je(we.TRTC.create)],H,"_create",1);var ru=H,Qo=ru;var su=class{constructor(){c(this,"_set",new Set);E.on(T.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,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function ST(){return f(this,null,function*(){let s,i;try{let h=yield st();s=h&&h.length}catch(h){}try{let h=yield pt();i=h&&h.length}catch(h){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Yt.basis(),d={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:d,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function Jm(){return q(s=>{let i=new su;return function(e,t,r){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:S.INVALID_OPERATION,message:U({key:x.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:S.INVALID_OPERATION,message:U({key:x.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),E.emit(T.JOIN_START,{room:this,roomId:o,params:e});let n=at.getEnv();n||(n=hi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(fn.OLD_CLOUD_LADDER)?n=hi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(fn.WEBRTC)&&(n=hi.WEBRTC))),ee.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Yt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,ST.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!at.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=at.performanceNow(),E.emit(T.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&ee.uploadEvent({log:`stat-conv-${Number(Ot)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),E.emit(T.JOIN_FAILED,{room:this,error:a}),a}})}})}var jm=()=>q(s=>function(...i){return f(this,null,function*(){E.emit(T.LEAVE_START,{room:this}),yield s.call(this,...i),E.emit(T.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function qm(){return q(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var zm=Ue(qe());var Ae={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var xt={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,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,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,RECEIVE_CUSTOM_MSG:4140},Xm=[xt.UPDATE_REMOTE_MUTE_STAT,xt.UPLINK_NETWORK_STATS,xt.USER_LIST_RES,xt.MUTE_RESULT,xt.SERVER_FIRST_PACKAGE_RECEIVED,xt.RECEIVE_CUSTOM_MSG],F={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",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-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",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},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",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",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",SEND_CUSTOM_MSG:"channel_msg"};var sc=new Set;function Qm(s){let i=[...sc.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Os=class extends zm.default{constructor(e){var r,o,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-sc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,sc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=C.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 race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),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 isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=L();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 mr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?p.BACKUP:p.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,d)=>{o.onclose=d,o.onerror=d,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?p.MAIN:p.BACKUP),d(new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}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===p.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){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.startReconnection(),this.room.isJoining&&this.emit(Ae.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ae.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Ks(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(xt),d=Object.keys(xt)[n.indexOf(r)],l=F[d]||r;switch(Xm.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case xt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Mu(o.svrTime),this._log.info(`ChannelSetup Success ${L()-this._connectStartTime}`),N.addSuccessEvent({key:521701,cost:L()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ae.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:U({key:x.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),N.addFailedEvent({key:521701,error:u}),this.emit(Ae.SETUP_FAILED,u)}break}case xt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;wt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?p.MAIN:p.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(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:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:X.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:F.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:L()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(N.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 r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=Ks(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,u)=>{let h=setTimeout(()=>{this.off(o,_);let R=new b({code:S.API_CALL_TIMEOUT,message:U({key:x.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(R),u(R)},r),m=Date.now(),_=R=>{R.data.seq===I&&(clearTimeout(h),this.off(o,_),d&&(R.data.receiveTime=Date.now()),l(R))};this.on(o,_);let I=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Wt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ae.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),sc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(F.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(F.JOIN_ROOM_RESULT,t))};this.on(F.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ae.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ae.CONNECTED):e==="DISCONNECTED"&&this.emit(Ae.DISCONNECTED))}};y([rt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Os.prototype,"connect",1);var Ym=Ue(qe());var ou=0,nu=!1,oc=new Set,AT=s=>ou>2&&!nu&&oc.size===0&&s,au=!1,Ze=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new Ym.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(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=C.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=L())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(L()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:L()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,N.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&N.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={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(),oc.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 b({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Ct;let i=null;if(this._isUplink){if(!Qi()||this._peerConnection.getSenders().length===0)return Ct;i=this._peerConnection.getSenders()[0].transport}else{if(!Ir()||this._peerConnection.getReceivers().length===0)return Ct;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Ct}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===he.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===he.FAILED||i.target.connectionState===he.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===he.CONNECTED||i.target.connectionState===he.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:et.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(ou=0,nu=!1,au=!0,oc.add(this)):oc.delete(this),E.emit(T.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 f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(zi(e)){let t=i.get(e.localCandidateId),r=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}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{E.off(T.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});ou+=1,AT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),nu=!0,this._emitter.emit("firewall-restriction")),e(a)},js);E.on(T.LEAVE_SUCCESS,r,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(Ae.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=mi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:U({key:this._isUplink?x.UPLINK_RECONNECTION_FAILED:x.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(Ae.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"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};y([ot(521712,!1)],Ze.prototype,"setOffer",1),y([ot(521713,!1)],Ze.prototype,"setAnswer",1);var uu=Ue(lu());var Ee=function(s){return uu.default.parse(s)},It=function(s){return uu.default.write(s)},op=function(s){let i=Ee(s);return i.media.forEach(e=>{e.type===p.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),It(i)};function np(s){let i=Ee(s);return i.media.forEach(e=>{var t,r;if(e.type===p.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),It(i)}function nc(s){return Object.keys(s).filter(i=>s[i])}var Ms=class Ms extends Ze{constructor(e){super(M(v({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Mi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ai(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Rs(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}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,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===Js?p.MAIN:p.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=p.AUDIO;r.kind===p.VIDEO&&(n=o===p.MAIN?p.VIDEO:p.AUXILIARY);let a=this.remoteAudioTrack;n===p.VIDEO?a=this.remoteVideoTrack:n===p.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
62
|
+
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,d]=o[n];t.splice(a+n,0,d)}return t.join(`\r
|
|
63
|
+
`)}addSPSDescription(e){let t=Ee(e);return t.media.forEach(r=>{r.type===p.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),It(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"],r=Ee(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),It(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===he.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===he.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${nc(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=X.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=X.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new b({code:a.code,message:U({key:x.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:X.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:F.SUBSCRIBE_RESULT,timeout:Lc});if(!this._peerConnection){let a=new b({code:S.INVALID_OPERATION,message:U({key:x.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};ut()&&this._sdpSemantics===Gi?(this._peerConnection.addTransceiver(p.AUDIO,{direction:Y.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:Y.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:Y.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield ia();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=np(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=op(t.sdp),this._sdpSemantics===Gi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===ar)throw new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:U({key:x.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ee(e).media.forEach(r=>{if(r.ssrcs)if(r.type===p.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Js)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(Js)}),n=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(vc)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(Ve(Ms.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=yt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}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}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};y([q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Ms.prototype,"subscribe",1),y([ot(521717,!1)],Ms.prototype,"unsubscribe",1),y([Qe(Ze.prototype.afterConnect),Ta(Ze.prototype.beforeConnect)],Ms.prototype,"connect",1);var hu=Ms,mu=hu;var cp={voiceActivityDetection:!1},Ls=class Ls extends Ze{constructor(e){super(M(v({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(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});c(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(zt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),ut()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),d&&a.addTrack(d);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||p.AUDIO,{direction:Y.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?p.VIDEO:d||p.VIDEO,{direction:Y.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||p.VIDEO,{direction:Y.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?d||p.VIDEO:p.VIDEO,{direction:Y.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(l&&(u[0].sender.track||h.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:p.AUDIO})),d){let m=o?3:1;yield u[m].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:p.VIDEO,videoType:o?p.AUXILIARY:p.BIG}),h.push(m),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:p.VIDEO,videoType:p.SMALL}),h.push(2))}yield this.setTransceiverDirection(Y.SENDONLY,h),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=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)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(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(Y.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Y.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(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!zt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=M(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=M(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(Y.INACTIVE,d),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 f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:X.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.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 r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Qt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:X.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(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?p.AUXILIARY:p.MAIN} stream`),ut()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Y.INACTIVE&&(yield this.setTransceiverDirection(Y.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;zt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===p.VIDEO&&e instanceof He&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Gr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Ee(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===p.VIDEO)return!0;return!1}removeSender(e){let t=null;zt()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ae(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(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?p.AUXILIARY:p.MAIN} stream`),ut()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Y.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!se)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,d=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
64
|
+
`).map(l=>{if(l.match(new RegExp(`a=(${Y.INACTIVE}|${Y.RECVONLY}|${Y.SENDONLY})`))&&a++,t.includes(a)){if(e===Y.INACTIVE&&l.includes(`a=${Y.RECVONLY}`))return o=!0,`a=${e}`;if(e===Y.SENDONLY&&l.includes(`a=${Y.INACTIVE}`))return o=!0,`a=${Y.RECVONLY}`}return l}).join(`\r
|
|
65
|
+
`);o&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:d}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===p.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===p.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===p.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(ut()?r=e.kind===p.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?p.AUXILIARY:p.MAIN} stream`),e.kind===p.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===p.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(cp);se&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===p.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:X.PUBLISH_CHANGE,data:n,responseCommand:F.UPDATE_OFFER_RESULT,timeout:Mc,commandDesc:"update offer"}),{code:d,message:l}=a.data;d!==0&&this.checkPublishResultCode(d,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:o}){if(!Co())return o?t===p.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e):void 0;let a,d=this._peerConnection.getSenders();if(ut()){let l=0;t===p.VIDEO&&(r===p.SMALL?l=2:r===p.AUXILIARY?l=3:l=1),a=d[l]}else a=d.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),o}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),o)return t===p.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,r){let o="AS";se&&(o="TIAS",t=t*1e3);let n=0,a=-1;return r===p.SMALL?n=1:r===p.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,d=>(a+=1,a===n?`${d}b=${o}:${t}\r
|
|
66
|
+
`:d)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return se&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
67
67
|
c=IN $2\r
|
|
68
68
|
b=${r}:${t}\r
|
|
69
|
-
`),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(mp);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Y.PUBLISH,responseCommand:G.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ct||this.localAuxVideoTrack instanceof ct,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:r,message:o,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,o)})}setSDPDirection(e,t,r="all"){let o=Ae(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),Rt(o)}acceptAnswer(e){return p(this,null,function*(){var t,r,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let u=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),f=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(u){let g=this._isPublishingAux?m.AUXILIARY:m.BIG;c=yield this.setBandwidth({bandwidth:u,type:m.VIDEO,sdp:c,videoType:g})}f&&(c=yield this.setBandwidth({bandwidth:f,type:m.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:u}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||u.bitrate,type:m.VIDEO,videoType:m.SMALL,sdp:c})}let h={type:e.type,sdp:c};yield this.setAnswer(h),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(Y.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Fe(ws.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,responseCommand:G.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 r=vt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(I.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ae(e).media.forEach((r,o)=>{if(r.type===m.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Jr&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===lr?(this._log.error(we.NOT_SUPPORTED_H264ENCODE),new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})})):new y({code:S.UNKNOWN,message:P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}};b([z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],ws.prototype,"publish",1),b([at(521715,!1)],ws.prototype,"unpublish",1),b([Ze(it.prototype.afterConnect),Ea(it.prototype.beforeConnect)],ws.prototype,"connect",1);var gu=ws,en=gu;var tn=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){var o;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(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var h,u,f;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===m.VIDEO){if(a.ssrc===r.video?(c=m.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=m.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=m.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,E(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),E(a.nackCount)||(e[c].nackCount=a.nackCount),E(a.pliCount)||(e[c].pliCount=a.pliCount),E(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),E(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),E(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!E(a.encoderImplementation)&&(c===m.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===m.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let D=2,_=this._prevEncoderImplementation;c===m.AUXILIARY&&(D=7,_=this._prevAuxEncoderImpl),T.emit("262",{userId:i.userId,streamType:D,prevImplementation:_,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===m.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===m.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!E(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(h=i.localMainVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!E(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(u=i.localAuxVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?Ki(a)&&(this.totalBytesSent=a.bytesSent,Q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===m.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===m.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(m.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!E(a.audioLevel)&&((f=i.localMainAudioTrack)!=null&&f.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!E(a.frameWidth)){let g=m.SMALL;a.trackIdentifier===i.getVideoTrackId(m.VIDEO)||a.ssrc===r.video?g=m.VIDEO:(a.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)||a.ssrc===r.auxiliary)&&(g=m.AUXILIARY),e[g].frameWidth=a.frameWidth,e[g].frameHeight=a.frameHeight,e[g].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===m.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===m.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===m.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return p(this,null,function*(){var r,o,n;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,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(u=>{if(u.type==="inbound-rtp"){let f=(u.mediaType||u.kind)===m.AUDIO;if(f){if(u.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=u.packetsReceived,e.audio.bytesReceived=u.bytesReceived,e.audio.packetsLost=u.packetsLost,u.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=u.insertedSamplesForDeceleration),u.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=u.removedSamplesForAcceleration),u.totalSamplesDuration&&(e.audio.totalSamplesDuration=u.totalSamplesDuration),u.totalSamplesReceived&&(e.audio.totalSamplesReceived=u.totalSamplesReceived),u.concealedSamples&&(e.audio.concealedSamples=u.concealedSamples);let{remoteAudioTrack:g}=i;g.stat.packetsReceived=u.packetsReceived,g.stat.bytesReceived=u.bytesReceived,g.stat.packetsLost=u.packetsLost,e.audio.p2pDelay=g.stat.end2EndDelay,e.hasAudio=!0}else{if(oe&&u.bytesReceived===0)return;let g;u.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=u.packetsReceived,e.video.bytesReceived=u.bytesReceived,e.video.packetsLost=u.packetsLost,e.video.framesReceived=u.framesReceived,e.video.framesDecoded=u.framesDecoded,e.video.fpsDecoded=u.framesPerSecond,e.hasVideo=!0,g=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),u.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==u.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${u.decoderImplementation} HWDecoder: ${u.powerEfficientDecoder}`),T.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:u.decoderImplementation,codec:i.videoCodec,isHWCodec:u.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,u.decoderImplementation))),u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=u.packetsReceived,e.auxiliary.bytesReceived=u.bytesReceived,e.auxiliary.packetsLost=u.packetsLost,e.auxiliary.framesReceived=u.framesReceived,e.auxiliary.framesDecoded=u.framesDecoded,e.auxiliary.fpsDecoded=u.framesPerSecond,g=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=g.stat.end2EndDelay,e.hasAuxiliary=!0),g&&(g.stat.packetsReceived=u.packetsReceived,g.stat.bytesReceived=u.bytesReceived,g.stat.packetsLost=u.packetsLost,g.stat.framesReceived=u.framesReceived,g.stat.framesDecoded=u.framesDecoded,u.jitterBufferDelay&&(g.stat.jitterBufferDelay=Math.floor(u.jitterBufferDelay/u.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=g.stat.end2EndDelay)}u.jitterBufferDelay&&(f?(e.audio.totalJitter=u.jitterBufferDelay,e.audio.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=u.jitterBufferDelay,e.video.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=u.jitterBufferDelay,e.auxiliary.totalJitterCount=u.jitterBufferEmittedCount))}else u.type==="candidate-pair"&&Ki(u)&&(this.totalBytesReceived=u.bytesReceived,Q(u.currentRoundTripTime)&&(e.rtt=Math.floor(u.currentRoundTripTime*1e3)));E(u.frameWidth)||((u.trackIdentifier===i.getMainStreamVideoTrackId()||u.ssrc===a.video)&&(e.video.frameWidth=u.frameWidth,e.video.frameHeight=u.frameHeight,i.remoteVideoTrack.stat.frameWidth=u.frameWidth,i.remoteVideoTrack.stat.frameHeight=u.frameHeight),(u.trackIdentifier===i.getAuxStreamVideoTrackId()||u.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=u.frameWidth,e.auxiliary.frameHeight=u.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=u.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=u.frameHeight)),!E(u.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&u.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=u.audioLevel||0,e.audio.totalAudioEnergy=u.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),E((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),E((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return p(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=x(),a=yield o.getStats(),c=x();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let l=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(u=>h.has(u.type)&&l.push(u)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(oi(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var f,g,D;if(!oi(i.senderStats)){let _={uint32_audio_level:i.senderStats.audio.audioLevel*Et,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(_.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Et),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let C=[];if(i.senderStats.video.bytesSent){let ne={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};C.push(ne)}if(i.senderStats.small.bytesSent){let ne={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};C.push(ne)}if(i.senderStats.auxiliary.bytesSent){let ne={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};C.push(ne)}let M={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:_,msg_video_status:C,msg_network_status:M}}let r=(f=Re())==null?void 0:f.playoutStats;r&&(e.msg_device_info.uint32_audio_play_cost=r.totalFramesDuration);let{statInterval:o}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(_=>{let C={msg_user_info:{str_identifier:_.userId,uint64_tinyid:_.tinyId},msg_network_status:{uint32_rtt:_.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(_.hasAudio){let M={uint32_audio_p2p_delay:_.audio.p2pDelay,uint32_audio_cache_ms:_.audio.totalJitter,uint32_audio_cache_ms_count:_.audio.totalJitterCount,uint32_audio_codec_bitrate:_.audio.bytesReceived,uint32_audio_total_bitrate:_.audio.bytesReceived,uint32_audio_level:_.audio.audioLevel*1e8,uint32_audio_energy:_.audio.totalAudioEnergy*1e6,uint32_audio_receive:_.audio.packetsReceived,uint32_audio_origin_lost:_.audio.packetsLost};C.msg_audio_status=M}if(_.hasVideo){let M=t.get(`${_.userId}_${kc}`),ne=M?M.duration:0,F={uint32_video_stream_type:_.isSmallSubscribed?3:2,uint32_video_receive_fps:_.video.framesReceived,uint32_video_width:_.video.frameWidth,uint32_video_height:_.video.frameHeight,uint32_video_codec_bitrate:_.video.bytesReceived,uint32_video_receive:_.video.packetsReceived,uint32_video_origin_lost:_.video.packetsLost,uint32_video_block_time:ne,uint32_video_dec_fps:_.video.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.video.totalJitter,uint32_video_cache_ms_count:_.video.totalJitterCount,uint32_video_p2p_delay:_.video.p2pDelay};C.msg_video_status.push(F)}if(_.hasAuxiliary){let M=t.get(`${_.userId}_${Lc}`),ne=M?M.duration:0,F={uint32_video_stream_type:7,uint32_video_receive_fps:_.auxiliary.framesReceived,uint32_video_width:_.auxiliary.frameWidth,uint32_video_height:_.auxiliary.frameHeight,uint32_video_codec_bitrate:_.auxiliary.bytesReceived,uint32_video_receive:_.auxiliary.packetsReceived+_.auxiliary.packetsLost,uint32_video_origin_lost:_.auxiliary.packetsLost,uint32_video_block_time:ne,uint32_video_dec_fps:_.auxiliary.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.auxiliary.totalJitter,uint32_video_cache_ms_count:_.auxiliary.totalJitterCount,uint32_video_p2p_delay:_.auxiliary.p2pDelay};C.msg_video_status.push(F)}e.msg_down_stream_info.push(C)});let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let _=n.msg_up_stream_info.msg_audio_status,C=e.msg_up_stream_info.msg_audio_status;if(_.uint32_audio_codec_bitrate===0)C.uint32_audio_codec_bitrate=0;else{let M=this.getDifferenceValue(_.uint32_audio_codec_bitrate,C.uint32_audio_codec_bitrate);C.uint32_audio_codec_bitrate=Math.round(M*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=C.uint32_audio_codec_bitrate}(g=n.msg_device_info)!=null&&g.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/o):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(_=>{let C=c.find(U=>U.uint32_video_stream_type===_.uint32_video_stream_type);if(!C||C.uint32_video_codec_bitrate===0){_.uint32_video_codec_bitrate=0,_.uint32_video_enc_fps=0,_.uint32_video_codec_fps=0;return}let M=0,ne=0,F=0;C&&_.uint32_video_codec_bitrate>=C.uint32_video_codec_bitrate&&(M=C.uint32_video_codec_bitrate,ne=C.uint32_video_enc_fps,F=C.uint32_video_codec_fps);let Oe=this.getDifferenceValue(M,_.uint32_video_codec_bitrate);_.uint32_video_codec_bitrate=Math.round(Oe*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_video_codec_bitrate,_.uint32_video_enc_fps=Math.round(this.getDifferenceValue(ne,_.uint32_video_enc_fps)/o),_.uint32_video_codec_fps=Math.round(this.getDifferenceValue(F,_.uint32_video_codec_fps)/o),C.uint32_video_width===0&&C.uint32_video_height===0&&C.uint32_video_codec_fps===0&&(_.uint32_video_codec_fps=_.uint32_video_enc_fps),E(C.uint32_key_frame_count)||(_.uint32_key_frame_count=Math.round(this.getDifferenceValue(C.uint32_key_frame_count,_.uint32_key_frame_count))),E(C.uint32_nack_count)||(_.uint32_nack_count=Math.round(this.getDifferenceValue(C.uint32_nack_count,_.uint32_nack_count))),E(C.uint32_pli_count)||(_.uint32_pli_count=Math.round(this.getDifferenceValue(C.uint32_pli_count,_.uint32_pli_count))),E(C.uint32_video_arq_packets)||(_.uint32_video_arq_packets=Math.round(this.getDifferenceValue(C.uint32_video_arq_packets,_.uint32_video_arq_packets))),E(C.uint32_encode_cost)||(_.uint32_encode_cost=Math.round(this.getDifferenceValue(C.uint32_encode_cost,_.uint32_encode_cost)/o)),E(C.uint32_send_packet_cost)||(_.uint32_send_packet_cost=Math.round(this.getDifferenceValue(C.uint32_send_packet_cost,_.uint32_send_packet_cost)/o))});let h=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(_=>h.find(C=>C.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid));let u=e.msg_down_stream_info;return u.forEach(_=>{let C=h.find(M=>M.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid);if(!oi(_.msg_audio_status)&&!oi(C.msg_audio_status)){let M=_.msg_audio_status,ne=C.msg_audio_status,F=this.getDifferenceValue(ne.uint32_audio_cache_ms_count,M.uint32_audio_cache_ms_count);delete M.uint32_audio_cache_ms_count,M.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(ne.uint32_audio_cache_ms,M.uint32_audio_cache_ms)/F)||0;let Oe=this.room.remotePublishedUserMap.get(_.msg_user_info.str_identifier);Oe&&(Oe.remoteAudioTrack.stat.jitterBufferDelay=M.uint32_audio_cache_ms),M.uint32_audio_origin_lost=this.getDifferenceValue(ne.uint32_audio_origin_lost,M.uint32_audio_origin_lost),M.uint32_audio_receive=this.getDifferenceValue(ne.uint32_audio_receive,M.uint32_audio_receive),M.uint32_audio_receive+=M.uint32_audio_origin_lost;let U=this.getDifferenceValue(ne.uint32_audio_codec_bitrate,M.uint32_audio_codec_bitrate);M.uint32_audio_codec_bitrate=Math.round(U*8/o),M.uint32_audio_total_bitrate=Math.round(U*8/o)}else _.msg_audio_status={};if(_.msg_video_status&&C.msg_video_status){let M=C.msg_video_status;_.msg_video_status=_.msg_video_status.filter(F=>M.find(Oe=>Oe.uint32_video_stream_type===F.uint32_video_stream_type)),_.msg_video_status.forEach(F=>{let Oe=M.find(Qp=>Qp.uint32_video_stream_type===F.uint32_video_stream_type),U=Oe.uint32_video_receive,Gp=Oe.uint32_video_origin_lost,Wp=Oe.uint32_video_codec_bitrate,Jp=Oe.uint32_video_receive_fps,jp=Oe.uint32_video_dec_fps;F.uint32_video_origin_lost=this.getDifferenceValue(Gp,F.uint32_video_origin_lost),F.uint32_video_receive=this.getDifferenceValue(U,F.uint32_video_receive)+F.uint32_video_origin_lost;let qp=this.getDifferenceValue(Wp,F.uint32_video_codec_bitrate);F.uint32_video_codec_bitrate=Math.round(qp*8/o);let Xp=this.getDifferenceValue(Jp,F.uint32_video_receive_fps);F.uint32_video_receive_fps=Math.round(Xp/o),F.uint32_video_dec_fps=Math.round(this.getDifferenceValue(jp,F.uint32_video_dec_fps)/o);let zp=this.getDifferenceValue(Oe.uint32_video_cache_ms_count,F.uint32_video_cache_ms_count);delete F.uint32_video_cache_ms_count,F.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Oe.uint32_video_cache_ms,F.uint32_video_cache_ms)/zp)||0})}}),(D=n.msg_device_info)!=null&&D.uint32_audio_play_cost?e.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_play_cost,e.msg_device_info.uint32_audio_play_cost)/o):delete e.msg_device_info.uint32_audio_play_cost,a&&i.receiverStats.forEach(_=>{if(_.audio.concealedSamples&&_.audio.totalSamplesReceived){let C=a.receiverStats.find(M=>M.userId===_.userId);if(C&&C.audio.concealedSamples&&C.audio.totalSamplesReceived){let M=_.audio.concealedSamples-C.audio.concealedSamples,ne=_.audio.totalSamplesReceived-C.audio.totalSamplesReceived,F=Math.floor(M/ne*1e3*o);if(F>o*1e3/5){let Oe=u.find(U=>U.msg_user_info.str_identifier===_.userId);Oe&&(Oe.msg_audio_status.uint32_audio_block_time=F)}}}}),e}getStatsReport(r){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},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_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var _p=Be(Qe());function pp(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),h=Math.round(t.secureConnectionStart-t.connectStart),u=Math.round(t.responseStart-t.requestStart),f=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=w(v({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:c,tcp:h,tls:l,request:u,response:f});break}}catch(e){}return i}function fp(s){return new Promise(i=>p(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=pp(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var FT=700,Br=class Br extends _p.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=R.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} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(G.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(ye.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===me.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:l,totalPacketsLost:h,totalPacketsReceived:u}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:u});continue}let f=0,g=this._downlinkPrevStatMap.get(c),D=h-g.totalPacketsLost,_=u-g.totalPacketsReceived;D<=0||_<0?f=0:f=Math.round(D/(D+_)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:u}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:f,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Rr())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&Q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===m.AUDIO||c.mediaType===m.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/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===me.DISCONNECTED||e.connectionState===me.FAILED||e.connectionState===me.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=re.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(I.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=w(v({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Br.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Br.lastPingTime>t.interval*1e3){Br.lastPingTime=Date.now();let a=t.domain.map(c=>fp(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>FT),this.pingResults.timestamp=o,this.pingResults.data=c,c.forEach(l=>{N.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}};d(Br,"EVENT_NETWORK_QUALITY","0"),d(Br,"lastPingTime",0);var xs=Br;function $T({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return qi(t)?t.catch(r=>R.error(`${s.name}() error observed ${r}`)):t}catch(t){R.error(`${s.name}() error observed ${t}`)}}}var lc=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);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=R.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&se(this[e])&&(this[e]=$T({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Me,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,fo().then(i=>{this._basicInfo.string_os_version=bi(),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("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(I.JOIN_START,this.handleJoinStart).addEvent(I.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(I.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(I.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(I.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(I.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(I.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(I.JOIN_FAILED,this.handleJoinFailed).addEvent(I.LEAVE_START,this.handleLeaveStart).addEvent(I.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(I.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(I.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(I.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(I.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(I.PUBLISH_START,this.handlePublishStart).addEvent(I.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(I.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(I.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(I.PLAY_TRACK_START,this.handlePlayStart).addEvent(I.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(I.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===m.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(I.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(I.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(I.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(I.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(I.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("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>T.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),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:r,dns:o,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}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 y?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 r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:w(v({},HT),{msg_user_info:new rn({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new rn({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),h=`${o}_${t}`,u=this._remoteStreamStatMap.get(h);u&&u.subscribeStartTime===0&&(u.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(h)&&this._pathMainVideoMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(h)&&this._pathMainAudioMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(h)&&this._pathAuxiliaryMap.set(h,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!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(!i.isRemote||!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(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,N.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}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:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,h,u;o&&(l=o,h=1),n&&(c=n,u=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:u,videoDelayCount:h})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/Et*100)>0&&(this._localStreamStat.totalAudioLevel+=o/Et,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,l=n.str_identifier,h=this._room.remotePublishedUserMap.get(l);if(c.forEach(u=>{let f=u.uint32_video_stream_type===2,g=u.uint32_video_stream_type===7,D=`${l}_${f?"main":"auxiliary"}`,_=this._remoteStreamStatMap.get(D);if(_&&(f&&(h!=null&&h.remoteVideoTrack.isSubscribed)||g&&(h!=null&&h.remoteAuxiliaryTrack))){_.totalVideoFPS+=u.uint32_video_receive_fps,_.totalVideoBitrate+=u.uint32_video_codec_bitrate,_.videoCount++,_.statsToReport.uint32_video_width===0&&(_.statsToReport.uint32_video_width=u.uint32_video_width),_.statsToReport.uint32_video_height===0&&(_.statsToReport.uint32_video_height=u.uint32_video_height);let C=f?h.remoteVideoTrack:h.remoteAuxiliaryTrack;C.stat.jitterBufferDelay&&(_.videoJitterBufferDelay=C.stat.jitterBufferDelay),C.stat.framesReceived&&(_.statsToReport.uint32_video_consume_render_rate=Math.floor(C.stat.framesDecoded/C.stat.framesReceived*Fs(10,6)))}}),!zr(a)){let u=`${l}_main`,f=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&f&&h!=null&&h.remoteAudioTrack.isSubscribed&&(f.totalAudioBitrate+=a.uint32_audio_codec_bitrate,f.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(f.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/Et*100)>0&&(f.totalAudioLevel+=a.uint32_audio_level/Et,f.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room: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 r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof y?e.getExtraCode()||e.getCode():S.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,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=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Wi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Ji)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&dr)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let 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,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:h,count:u,audioDelayCount:f,videoDelayCount:g,totalAudioDelay:D,totalVideoDelay:_}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(h/u),f&&D&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(D/f),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),g&&_&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(_/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:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,m.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,m.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Fr));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),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>Fr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Fr)}),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>Fr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Fr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Fr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Fr)}getReportData(){this._basicInfo.uint32_networkType=mr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new rn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Qr(this._signalInfo.relayIp),uint32_client_ip:Qr(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Fs(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:Qr(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return to(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return p(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield Gc(i),r=t instanceof ArrayBuffer,o=`${Ei(e,Gi.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(N),this.uploadKVStat(Ar)];n||a.push(Ai({url:o,body:t,priority:"low"})),yield Promise.all(a)})}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=w(v({},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 Gc(e),r=`${Ei(+this._room.sdkAppId,Gi.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||Ai({url:r,body:t})})}};b([ot({settings:{timeout:500,retries:3}})],lc.prototype,"upload",1);var Fr=5e3,HT={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_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},rn=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},gp=lc;var Tu=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=x())}stop(){this._endTime===0&&(this._endTime=x())}getDuration(){return this._endTime===0?x()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},uc=Tu;var Eu=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(I.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(I.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(I.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,m.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,m.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,m.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);o&&(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,m.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,m.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,m.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({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new uc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===m.AUDIO?[o]:[],video:e===m.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(o=>o.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,o)=>r+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Tp=Eu;var Su=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new Map);d(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(I.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(I.PLAY_TRACK_START,this.onPlayTrackStart).set(I.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(I.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(I.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==m.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===m.MUTE?this.onVideoTrackMuted(i):t===m.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(I.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,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new uc;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){this.hitTest(i)&&e.msg_down_stream_info.forEach(t=>{let r=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!r)return;let{userId:o,muteState:n}=r;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&r.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let n=o.getDuration();n>En?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return p(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=x();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=x();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==m.VIDEO||!i.isRemotePublished)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 r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<En&&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,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=x(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}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()}},Ep=Su;var Ip=Be(Qe(),1);var GT=[1,0,0,0,1,1,0,1],hc=class extends tt{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof De)try{this.setTexBuffer(GT)}catch(t){i.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,r,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,r,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Iu=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},mc=class extends tt{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new Iu(e,t);this.inputs[t.zIndex]=r}resize(e,t){let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof De&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((r,o)=>(!o||!o.node.requestFrame(e))&&r,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:l,name:a},v({parent:this.inputs.filter(h=>h).map(h=>h.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof De))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var WT=`#version 300 es
|
|
69
|
+
`),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 f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(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 f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(cp);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:X.PUBLISH,responseCommand:F.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof nt||this.localAuxVideoTrack instanceof nt,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:r,message:o,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,o)})}setSDPDirection(e,t,r="all"){let o=Ee(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),It(o)}acceptAnswer(e){return f(this,null,function*(){var t,r,o,n,a;try{let d;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),m=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(h){let _=this._isPublishingAux?p.AUXILIARY:p.BIG;d=yield this.setBandwidth({bandwidth:h,type:p.VIDEO,sdp:d,videoType:_})}m&&(d=yield this.setBandwidth({bandwidth:m,type:p.AUDIO,sdp:d}))}if(d=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;d=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:p.VIDEO,videoType:p.SMALL,sdp:d})}let u={type:e.type,sdp:d};yield this.setAnswer(u),this._log.debug(`accepted answer: ${d}`)}catch(d){throw this._log.error(`failed to accept remote answer ${d}`),d}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(X.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(Ve(Ls.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,responseCommand:F.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 r=yt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(T.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ee(e).media.forEach((r,o)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Gr&&r.ssrcGroups){r.ssrcGroups.forEach((a,d)=>{let l=Number(a.ssrcs.split(" ")[0]);d===0?this.ssrc.video=l:d===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===ar?(this._log.error(Me.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:U({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}};y([q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Ls.prototype,"publish",1),y([ot(521715,!1)],Ls.prototype,"unpublish",1),y([Qe(Ze.prototype.afterConnect),Ta(Ze.prototype.beforeConnect)],Ls.prototype,"connect",1);var pu=Ls,Ko=pu;var Zo=class{constructor(i,e){this.room=i;c(this,"_log");c(this,"_prevReportTime",0);c(this,"_prevReport",{});c(this,"_prevStats",null);c(this,"_prevEncoderImplementation","");c(this,"_prevAuxEncoderImpl","");c(this,"_prevQualityLimitationReason","");c(this,"_prevAuxQualityLimitationReason","");c(this,"_prevDecoderImplementationMap",new Map);c(this,"totalBytesSent",0);c(this,"totalBytesReceived",0);c(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var o;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(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,h,m;let d,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(d=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?d=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,d=p.AUXILIARY),!d)return;if(e[d].bytesSent=a.bytesSent,e[d].packetsSent=a.packetsSent,e[d].framesEncoded=a.framesEncoded,g(a.keyFramesEncoded)||(e[d].keyFramesEncoded=a.keyFramesEncoded),g(a.nackCount)||(e[d].nackCount=a.nackCount),g(a.pliCount)||(e[d].pliCount=a.pliCount),g(a.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=a.retransmittedPacketsSent),g(a.totalEncodeTime)||(e[d].totalEncodeTime=a.totalEncodeTime),g(a.totalPacketSendDelay)||(e[d].totalPacketSendDelay=a.totalPacketSendDelay),!g(a.encoderImplementation)&&(d===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||d===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let I=2,R=this._prevEncoderImplementation;d===p.AUXILIARY&&(I=7,R=this._prevAuxEncoderImpl),E.emit("262",{userId:i.userId,streamType:I,prevImplementation:R,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[d===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${d===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!g(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(u=i.localMainVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!g(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(h=i.localAuxVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?zi(a)&&(this.totalBytesSent=a.bytesSent,Q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===p.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===p.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(p.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!g(a.audioLevel)&&((m=i.localMainAudioTrack)!=null&&m.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!g(a.frameWidth)){let _=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?_=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(_=p.AUXILIARY),e[_].frameWidth=a.frameWidth,e[_].frameHeight=a.frameHeight,e[_].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,o,n;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,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:d,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{if(h.type==="inbound-rtp"){let m=(h.mediaType||h.kind)===p.AUDIO;if(m){if(h.ssrc!==a.audio||!d.hasAudio)return;e.audio.packetsReceived=h.packetsReceived,e.audio.bytesReceived=h.bytesReceived,e.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(e.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(e.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(e.audio.concealedSamples=h.concealedSamples);let{remoteAudioTrack:_}=i;_.stat.packetsReceived=h.packetsReceived,_.stat.bytesReceived=h.bytesReceived,_.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=_.stat.end2EndDelay,e.hasAudio=!0}else{if(se&&h.bytesReceived===0)return;let _;h.ssrc===a.video&&d.hasVideo&&(e.video.packetsReceived=h.packetsReceived,e.video.bytesReceived=h.bytesReceived,e.video.packetsLost=h.packetsLost,e.video.framesReceived=h.framesReceived,e.video.framesDecoded=h.framesDecoded,e.video.fpsDecoded=h.framesPerSecond,e.hasVideo=!0,_=i.remoteVideoTrack,d.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==h.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${h.decoderImplementation} HWDecoder: ${h.powerEfficientDecoder}`),E.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:h.decoderImplementation,codec:i.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,h.decoderImplementation))),h.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.packetsReceived=h.packetsReceived,e.auxiliary.bytesReceived=h.bytesReceived,e.auxiliary.packetsLost=h.packetsLost,e.auxiliary.framesReceived=h.framesReceived,e.auxiliary.framesDecoded=h.framesDecoded,e.auxiliary.fpsDecoded=h.framesPerSecond,_=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),_&&(_.stat.packetsReceived=h.packetsReceived,_.stat.bytesReceived=h.bytesReceived,_.stat.packetsLost=h.packetsLost,_.stat.framesReceived=h.framesReceived,_.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(_.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)))}h.jitterBufferDelay&&(m?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.video&&d.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&zi(h)&&(this.totalBytesReceived=h.bytesReceived,Q(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));g(h.frameWidth)||((h.trackIdentifier===i.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(e.video.frameWidth=h.frameWidth,e.video.frameHeight=h.frameHeight,i.remoteVideoTrack.stat.frameWidth=h.frameWidth,i.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===i.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=h.frameWidth,e.auxiliary.frameHeight=h.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!g(h.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&h.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=h.audioLevel||0,e.audio.totalAudioEnergy=h.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),g((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),g((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=L(),a=yield o.getStats(),d=L();d-n>2e3&&this._log.warn(`getStats cost ${d-n}ms`);let l=[],u=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(h=>u.has(h.type)&&l.push(h)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(ti(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var h;if(!ti(i.senderStats)){let m={uint32_audio_level:i.senderStats.audio.audioLevel*gt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(m.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*gt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let _=[];if(i.senderStats.video.bytesSent){let R={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};_.push(R)}if(i.senderStats.small.bytesSent){let R={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};_.push(R)}if(i.senderStats.auxiliary.bytesSent){let R={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};_.push(R)}let I={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:m,msg_video_status:_,msg_network_status:I}}let{statInterval:r}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(m=>{let _={msg_user_info:{str_identifier:m.userId,uint64_tinyid:m.tinyId},msg_network_status:{uint32_rtt:m.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(m.hasAudio){let I={uint32_audio_p2p_delay:m.audio.p2pDelay,uint32_audio_cache_ms:m.audio.totalJitter,uint32_audio_cache_ms_count:m.audio.totalJitterCount,uint32_audio_codec_bitrate:m.audio.bytesReceived,uint32_audio_total_bitrate:m.audio.bytesReceived,uint32_audio_level:m.audio.audioLevel*1e8,uint32_audio_energy:m.audio.totalAudioEnergy*1e6,uint32_audio_receive:m.audio.packetsReceived,uint32_audio_origin_lost:m.audio.packetsLost};_.msg_audio_status=I}if(m.hasVideo){let I=t.get(`${m.userId}_${Dc}`),R=I?I.duration:0,D={uint32_video_stream_type:m.isSmallSubscribed?3:2,uint32_video_receive_fps:m.video.framesReceived,uint32_video_width:m.video.frameWidth,uint32_video_height:m.video.frameHeight,uint32_video_codec_bitrate:m.video.bytesReceived,uint32_video_receive:m.video.packetsReceived,uint32_video_origin_lost:m.video.packetsLost,uint32_video_block_time:R,uint32_video_dec_fps:m.video.framesDecoded,uint32_video_codec_fps:m.video.fpsRender,uint32_video_cache_ms:m.video.totalJitter,uint32_video_cache_ms_count:m.video.totalJitterCount};_.msg_video_status.push(D)}if(m.hasAuxiliary){let I=t.get(`${m.userId}_${Oc}`),R=I?I.duration:0,D={uint32_video_stream_type:7,uint32_video_receive_fps:m.auxiliary.framesReceived,uint32_video_width:m.auxiliary.frameWidth,uint32_video_height:m.auxiliary.frameHeight,uint32_video_codec_bitrate:m.auxiliary.bytesReceived,uint32_video_receive:m.auxiliary.packetsReceived+m.auxiliary.packetsLost,uint32_video_origin_lost:m.auxiliary.packetsLost,uint32_video_block_time:R,uint32_video_dec_fps:m.auxiliary.framesDecoded,uint32_video_codec_fps:m.video.fpsRender,uint32_video_cache_ms:m.auxiliary.totalJitter,uint32_video_cache_ms_count:m.auxiliary.totalJitterCount};_.msg_video_status.push(D)}e.msg_down_stream_info.push(_)});let o=this._prevReport,n=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let m=o.msg_up_stream_info.msg_audio_status,_=e.msg_up_stream_info.msg_audio_status;if(m.uint32_audio_codec_bitrate===0)_.uint32_audio_codec_bitrate=0;else{let I=this.getDifferenceValue(m.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(I*8/r),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_audio_codec_bitrate}(h=o.msg_device_info)!=null&&h.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/r):delete e.msg_device_info.uint32_audio_capture_cost}let a=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(m=>{let _=a.find(te=>te.uint32_video_stream_type===m.uint32_video_stream_type);if(!_||_.uint32_video_codec_bitrate===0){m.uint32_video_codec_bitrate=0,m.uint32_video_enc_fps=0,m.uint32_video_codec_fps=0;return}let I=0,R=0,D=0;_&&m.uint32_video_codec_bitrate>=_.uint32_video_codec_bitrate&&(I=_.uint32_video_codec_bitrate,R=_.uint32_video_enc_fps,D=_.uint32_video_codec_fps);let W=this.getDifferenceValue(I,m.uint32_video_codec_bitrate);m.uint32_video_codec_bitrate=Math.round(W*8/r),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_video_codec_bitrate,m.uint32_video_enc_fps=Math.round(this.getDifferenceValue(R,m.uint32_video_enc_fps)/r),m.uint32_video_codec_fps=Math.round(this.getDifferenceValue(D,m.uint32_video_codec_fps)/r),_.uint32_video_width===0&&_.uint32_video_height===0&&_.uint32_video_codec_fps===0&&(m.uint32_video_codec_fps=m.uint32_video_enc_fps),g(_.uint32_key_frame_count)||(m.uint32_key_frame_count=Math.round(this.getDifferenceValue(_.uint32_key_frame_count,m.uint32_key_frame_count))),g(_.uint32_nack_count)||(m.uint32_nack_count=Math.round(this.getDifferenceValue(_.uint32_nack_count,m.uint32_nack_count))),g(_.uint32_pli_count)||(m.uint32_pli_count=Math.round(this.getDifferenceValue(_.uint32_pli_count,m.uint32_pli_count))),g(_.uint32_video_arq_packets)||(m.uint32_video_arq_packets=Math.round(this.getDifferenceValue(_.uint32_video_arq_packets,m.uint32_video_arq_packets))),g(_.uint32_encode_cost)||(m.uint32_encode_cost=Math.round(this.getDifferenceValue(_.uint32_encode_cost,m.uint32_encode_cost)/r)),g(_.uint32_send_packet_cost)||(m.uint32_send_packet_cost=Math.round(this.getDifferenceValue(_.uint32_send_packet_cost,m.uint32_send_packet_cost)/r))});let l=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(m=>l.find(_=>_.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid));let u=e.msg_down_stream_info;return u.forEach(m=>{let _=l.find(I=>I.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid);if(!ti(m.msg_audio_status)&&!ti(_.msg_audio_status)){let I=m.msg_audio_status,R=_.msg_audio_status,D=this.getDifferenceValue(R.uint32_audio_cache_ms_count,I.uint32_audio_cache_ms_count);delete I.uint32_audio_cache_ms_count,I.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(R.uint32_audio_cache_ms,I.uint32_audio_cache_ms)/D)||0;let W=this.room.remotePublishedUserMap.get(m.msg_user_info.str_identifier);W&&(W.remoteAudioTrack.stat.jitterBufferDelay=I.uint32_audio_cache_ms),I.uint32_audio_origin_lost=this.getDifferenceValue(R.uint32_audio_origin_lost,I.uint32_audio_origin_lost),I.uint32_audio_receive=this.getDifferenceValue(R.uint32_audio_receive,I.uint32_audio_receive),I.uint32_audio_receive+=I.uint32_audio_origin_lost;let te=this.getDifferenceValue(R.uint32_audio_codec_bitrate,I.uint32_audio_codec_bitrate);I.uint32_audio_codec_bitrate=Math.round(te*8/r),I.uint32_audio_total_bitrate=Math.round(te*8/r)}else m.msg_audio_status={};if(m.msg_video_status&&_.msg_video_status){let I=_.msg_video_status;m.msg_video_status=m.msg_video_status.filter(D=>I.find(W=>W.uint32_video_stream_type===D.uint32_video_stream_type)),m.msg_video_status.forEach(D=>{let W=I.find(Gp=>Gp.uint32_video_stream_type===D.uint32_video_stream_type),te=W.uint32_video_receive,on=W.uint32_video_origin_lost,Vp=W.uint32_video_codec_bitrate,z=W.uint32_video_receive_fps,Bp=W.uint32_video_dec_fps;D.uint32_video_origin_lost=this.getDifferenceValue(on,D.uint32_video_origin_lost),D.uint32_video_receive=this.getDifferenceValue(te,D.uint32_video_receive)+D.uint32_video_origin_lost;let Fp=this.getDifferenceValue(Vp,D.uint32_video_codec_bitrate);D.uint32_video_codec_bitrate=Math.round(Fp*8/r);let $p=this.getDifferenceValue(z,D.uint32_video_receive_fps);D.uint32_video_receive_fps=Math.round($p/r),D.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Bp,D.uint32_video_dec_fps)/r);let Hp=this.getDifferenceValue(W.uint32_video_cache_ms_count,D.uint32_video_cache_ms_count);delete D.uint32_video_cache_ms_count,D.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(W.uint32_video_cache_ms,D.uint32_video_cache_ms)/Hp)||0})}}),n&&i.receiverStats.forEach(m=>{if(m.audio.concealedSamples&&m.audio.totalSamplesReceived){let _=n.receiverStats.find(I=>I.userId===m.userId);if(_&&_.audio.concealedSamples&&_.audio.totalSamplesReceived){let I=m.audio.concealedSamples-_.audio.concealedSamples,R=m.audio.totalSamplesReceived-_.audio.totalSamplesReceived,D=Math.floor(I/R*1e3*r);if(D>r*1e3/5){let W=u.find(te=>te.msg_user_info.str_identifier===m.userId);W&&(W.msg_audio_status.uint32_audio_block_time=D)}}}}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},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_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var up=Ue(qe());function dp(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,d=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),h=Math.round(t.responseStart-t.requestStart),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=M(v({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:d,tcp:u,tls:l,request:h,response:m});break}}catch(e){}return i}function lp(s){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=dp(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var MT=700,Ur=class Ur extends up.default{constructor({signalChannel:e,room:t}){super();c(this,"_room");c(this,"_signalChannel");c(this,"_log");c(this,"uplinkRTT",0);c(this,"uplinkLoss",0);c(this,"downlinkRTT",0);c(this,"downlinkLoss",0);c(this,"pingResults",{});c(this,"_downlinkPrevStatMap",new Map);c(this,"_downlinkLossAndRTTMap",new Map);c(this,"_interval",-1);c(this,"_uplinkNetworkQuality",0);c(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=C.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} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(F.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ae.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var d,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(d=this._room)==null?void 0:d.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var d;return((d=a.getPeerConnection())==null?void 0:d.connectionState)===he.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 d=t[a].getPeerConnection();if(!d)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:h}=yield this.getStat(d);if(!this._downlinkPrevStatMap.has(d)){this._downlinkPrevStatMap.set(d,{totalPacketsLost:u,totalPacketsReceived:h});continue}let m=0,_=this._downlinkPrevStatMap.get(d),I=u-_.totalPacketsLost,R=h-_.totalPacketsReceived;I<=0||R<0?m=0:m=Math.round(I/(I+R)*100),this._downlinkPrevStatMap.set(d,{totalPacketsLost:u,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(d,{rtt:l,loss:m,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){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Ir())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(d=>{d.type==="candidate-pair"&&Q(d.currentRoundTripTime)&&(t.rtt=Math.round(d.currentRoundTripTime*1e3)),d.type==="inbound-rtp"&&(d.mediaType===p.AUDIO||d.mediaType===p.VIDEO)&&(t.totalPacketsLost+=d.packetsLost,t.totalPacketsReceived+=d.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/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===he.DISCONNECTED||e.connectionState===he.FAILED||e.connectionState===he.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=re.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];E.emit(T.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=M(v({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Ur.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Ur.lastPingTime>t.interval*1e3){Ur.lastPingTime=Date.now();let a=t.domain.map(d=>lp(d).then(l=>({domain:d,cost:l.totalCost})));Promise.all(a).then(d=>{this.pingResults.isPoorNetwork=d.some(l=>l.cost>MT),this.pingResults.timestamp=o,this.pingResults.data=d,d.forEach(l=>{N.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(d)}`)}).catch(d=>{this._log.warn(`Error during pinging domains: ${d}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let d=this._room.remotePublishedUserMap.get(a);d==null||d.setDelay({videoDelay:o,audioDelay:n})}})}};c(Ur,"EVENT_NETWORK_QUALITY","0"),c(Ur,"lastPingTime",0);var Ps=Ur;function LT({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return Wi(t)?t.catch(r=>C.error(`${s.name}() error observed ${r}`)):t}catch(t){C.error(`${s.name}() error observed ${t}`)}}}var ac=class{constructor(i){c(this,"_frameWorkType");c(this,"_component");c(this,"_language");c(this,"connectionType");c(this,"_room");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});c(this,"_keyPrefix");c(this,"_log");c(this,"_intervalId");c(this,"_firstPublishedUserList");c(this,"_networkQuality");c(this,"_basicInfo");c(this,"_pathJoinRoom");c(this,"_pathLeaveRoom");c(this,"_pathMainVideoMap");c(this,"_pathMainAudioMap");c(this,"_pathAuxiliaryMap");c(this,"_remoteStreamStatMap");c(this,"_localStreamStat");c(this,"_eventMap",new Map);c(this,"_captureCostSum",0);c(this,"_captureCostCount",0);c(this,"isDestroyed",!1);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=C.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ae(this[e])&&(this[e]=LT({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:ve,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,mo().then(i=>{this._basicInfo.string_os_version=Ai(),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),E.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(T.JOIN_START,this.handleJoinStart).addEvent(T.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(T.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(T.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(T.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(T.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(T.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(T.JOIN_FAILED,this.handleJoinFailed).addEvent(T.LEAVE_START,this.handleLeaveStart).addEvent(T.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(T.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(T.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(T.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(T.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(T.PUBLISH_START,this.handlePublishStart).addEvent(T.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(T.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(T.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(T.PLAY_TRACK_START,this.handlePlayStart).addEvent(T.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(T.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(T.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(T.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(T.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(T.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(T.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("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>E.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(g(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),g(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),g(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:r,dns:o,tcp:n,tls:a,request:d,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=l}}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 b?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 r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:M(v({},PT),{msg_user_info:new en({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,d=new en({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${o}_${t}`,h=this._remoteStreamStatMap.get(u);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!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(!i.isRemote||!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(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,N.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}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:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,l,u,h;o&&(l=o,u=1),n&&(d=n,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:d,totalVideoDelay:l,audioDelayCount:h,videoDelayCount:u})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:d}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=d,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/gt*100)>0&&(this._localStreamStat.totalAudioLevel+=o/gt,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:d}=o,l=n.str_identifier,u=this._room.remotePublishedUserMap.get(l);if(d.forEach(h=>{let m=h.uint32_video_stream_type===2,_=h.uint32_video_stream_type===7,I=`${l}_${m?"main":"auxiliary"}`,R=this._remoteStreamStatMap.get(I);if(R&&(m&&(u!=null&&u.remoteVideoTrack.isSubscribed)||_&&(u!=null&&u.remoteAuxiliaryTrack))){R.totalVideoFPS+=h.uint32_video_receive_fps,R.totalVideoBitrate+=h.uint32_video_codec_bitrate,R.videoCount++,R.statsToReport.uint32_video_width===0&&(R.statsToReport.uint32_video_width=h.uint32_video_width),R.statsToReport.uint32_video_height===0&&(R.statsToReport.uint32_video_height=h.uint32_video_height);let D=m?u.remoteVideoTrack:u.remoteAuxiliaryTrack;D.stat.jitterBufferDelay&&(R.videoJitterBufferDelay=D.stat.jitterBufferDelay),D.stat.framesReceived&&(R.statsToReport.uint32_video_consume_render_rate=Math.floor(D.stat.framesDecoded/D.stat.framesReceived*Vs(10,6)))}}),!qr(a)){let h=`${l}_main`,m=this._remoteStreamStatMap.get(h);this._remoteStreamStatMap.has(h)&&m&&u!=null&&u.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/gt*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/gt,m.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room: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 r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof b?e.getExtraCode()||e.getCode():S.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,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=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&$i)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Hi)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&nr)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let 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,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:h,audioDelayCount:m,videoDelayCount:_,totalAudioDelay:I,totalVideoDelay:R}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),m&&I&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(I/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&R&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(R/_))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Vr));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:d}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=d,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),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>Vr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Vr)}),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>Vr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Vr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Vr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Vr)}getReportData(){this._basicInfo.uint32_networkType=ur();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new en({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Xr(this._signalInfo.relayIp),uint32_client_ip:Xr(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Vs(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:Xr(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Zs(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield Fc(i),r=t instanceof ArrayBuffer,o=`${fi(e,Fi.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(N),this.uploadKVStat(Sr)];n||a.push(Ti({url:o,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(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(v({},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 Fc(e),r=`${fi(+this._room.sdkAppId,Fi.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||Ti({url:r,body:t})})}};y([rt({settings:{timeout:500,retries:3}})],ac.prototype,"upload",1);var Vr=5e3,PT={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_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},en=class{constructor(i){c(this,"str_identifier");c(this,"str_tinyid");c(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},hp=ac;var fu=class{constructor(){c(this,"_startTime");c(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=L())}stop(){this._endTime===0&&(this._endTime=L())}getDuration(){return this._endTime===0?L()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},cc=fu;var _u=class{constructor(i){c(this,"_room",null);c(this,"_durationMap");c(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(T.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(T.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(T.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);o&&(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new cc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[o]:[],video:e===p.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(o=>o.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,o)=>r+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},mp=_u;var gu=class{constructor(i){c(this,"_room");c(this,"_renderFreezeMap",new Map);c(this,"_isVideoPlayingEventFiredMap",new Map);c(this,"_dataFreezeMap",new Map);c(this,"_monitorFreezeData",new Map);c(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(T.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(T.PLAY_TRACK_START,this.onPlayTrackStart).set(T.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(T.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(T.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(T.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new cc;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){this.hitTest(i)&&e.msg_down_stream_info.forEach(t=>{let r=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!r)return;let{userId:o,muteState:n}=r;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&r.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let n=o.getDuration();n>Tn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return f(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=L();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=L();let d=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,d)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.VIDEO||!i.isRemotePublished)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 r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Tn&&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,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=L(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}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()}},pp=gu;var _p=Ue(qe(),1);var wT=[1,0,0,0,1,1,0,1],dc=class extends Ke{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof Ne)try{this.setTexBuffer(wT)}catch(t){i.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,r,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,r,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Tu=class{constructor(i,e){this.node=i;this.layout=e;c(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}},lc=class extends Ke{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});c(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new Tu(e,t);this.inputs[t.zIndex]=r}resize(e,t){let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Ne&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((r,o)=>(!o||!o.node.requestFrame(e))&&r,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:d,fps:l,name:a},v({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof Ne))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var xT=`#version 300 es
|
|
70
70
|
in vec2 a_position;
|
|
71
71
|
in vec2 a_texCoord;
|
|
72
72
|
out vec2 v_texCoord;
|
|
73
73
|
void main() {
|
|
74
74
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
75
75
|
v_texCoord = a_texCoord;
|
|
76
|
-
}`,
|
|
76
|
+
}`,UT=`#version 300 es
|
|
77
77
|
precision highp float;
|
|
78
78
|
uniform sampler2D u_texture;
|
|
79
79
|
uniform sampler2D mask;
|
|
@@ -82,7 +82,7 @@ in vec2 v_texCoord;
|
|
|
82
82
|
out vec4 outColor;
|
|
83
83
|
void main() {
|
|
84
84
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
85
|
-
}`,
|
|
85
|
+
}`,uc=class extends wi{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});c(this,"_bgTexture");c(this,"_waterMarkTexture");c(this,"_lastMaskTexture");c(this,"_lastMaskFbo");c(this,"_textureValid",!1);c(this,"_selfieTextureValid",!1);c(this,"_selfieSegmentation");c(this,"wasm");c(this,"_prePrograme");c(this,"_segmentationMask");c(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(r){e.log.error(r),e.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))}}init(e){let t=e.Wasm,r=this.context.ctx;if(this.wasm=new t.AllIn1(r),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:o,y:n,width:a,height:d}=e.waterMark;this.wasm.setWaterMark(o,n,a,d)}if(e.beautyParams){let{beauty:o,brightness:n,ruddy:a}=e.beautyParams;this.wasm.setBeauty(o,n,a,e==null?void 0:e.width,e==null?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let o=this.context.createShader(r.FRAGMENT_SHADER,UT),n=this.context.createShader(r.VERTEX_SHADER,xT);this._prePrograme=this.context.createProgram(n,o),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var r;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==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(r=this._selfieSegmentation)==null||r.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++}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){var d,l,u,h;let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:o,videoHeight:n}=r;if(o===0||n===0||!this.available)return!1;r.width=o,r.height=n;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():(d=this._selfieSegmentation)==null||d.bindTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}return this.width!==o||this.height!==n||!a?(this.resize(o,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(l=this._selfieSegmentation)==null||l.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(u=this._selfieSegmentation)==null||u.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,o,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,o,n,0)),this.wasm.vbMode&&((h=this._selfieSegmentation)==null||h.send(o,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 hc=class extends Ke{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
86
86
|
precision highp float;
|
|
87
87
|
uniform sampler2D ySampler;
|
|
88
88
|
uniform sampler2D uSampler;
|
|
@@ -107,13 +107,13 @@ void main() {
|
|
|
107
107
|
void main() {
|
|
108
108
|
gl_Position = vertexPos;
|
|
109
109
|
textureCoord = texturePos;
|
|
110
|
-
}`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,o=r.createTexture();return r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),o}render(e){let t=this.context.ctx,r=this.width,o=this.height;return this.useProgram(),t.viewport(0,0,r,o),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,o,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var Au=[s=>{s.codec="avc1.420028"},s=>{delete s.hardwareAcceleration}],Sp=(s,i)=>{switch(s){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function jT(s){return s[0]===0&&s[1]===0&&s[2]===0&&s[3]===1}var qT=0,_c=class{constructor(i){d(this,"id",qT++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=et(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=ue(e.availableState,H.OFF),this.stopOB=et(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),de(this.stateChangeOB,kl((r,o)=>(r!==o&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:o}),o),"INITIALIZED"),xe(this.stopOB),Ce()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=de(this.pipe(this.track),xe(this.stopOB),xi());de(e,Ce(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),N.addFailedEvent({key:Sp(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),N.addSuccessEvent({key:Sp(this.type,this.renderer)}),N.addSuccessEvent({key:514704})})),de(e,Ui(1),Ce(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!Dd()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!jT(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,o=!1;switch(r){case 5:case 7:o=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),o&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(o)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=x();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(c=i.getMetadata)==null?void 0:c.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>p(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:o,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":for(let c=0;c<=Au.length;c++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(c===Au.length){e.error(3);return}Au[c](this.config)}t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&o==="webgl"){this.videoContext=new De({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(De.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new fc(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(o==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",h=>l.write(h))}else{this.videoContext=new je({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",h=>{try{c.image=h,c.update()}catch(u){delete this.goodType,i.log.error(u),e.error(11)}});let l=new Pr(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var sn=class extends Ip.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"cameraTrack");d(this,"cameraNode");d(this,"mirrorNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log",R.createLogger({id:"vm"}));d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"_selfieSegmentation");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);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._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new De({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(De.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{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(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(zi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?N.addFailedEvent({key:r,error:t}):N.addSuccessEvent({key:r})}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{if(this._glVideoContext=new De({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}setSmallVideo(e,t){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new $a(this.smallVideoContext,e,this.log),this.smallVideoContext.on(De.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:o}=this.cameraTrack.settings;this.smallTrackSource.resize(r,o),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:o,player:n}=r;this.setSmallVideo(o,e),zi&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${a?a.label:"no output track"}`),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return p(this,null,function*(){var o,n,a;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),ut===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Vi?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Vi?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Fa(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new pc(this.videoContext,{input:this.initialTrack,width:t.width,height:t.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let c=this.cameraNode;c.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new hc(this.videoContext,this.log)),c=c.connect(this.mirrorNode),c.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new mc(this.videoContext,this.log),c.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption?(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y):(o=this.waterMarkNode)==null||o.resize(t.width,t.height),(n=this.waterMarkNode)==null||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(a=this.screenNode)==null||a.connect(this.mixNode,{zIndex:0}),c=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),c.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof ct)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Je)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof ui){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof ct?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Je?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ui&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update(!0)})}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 r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let o=r.getContext("2d");if(!o)throw new y({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:h})=>{o.drawImage(n,a,c,l,h)}),Kr(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return p(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return p(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return p(this,null,function*(){var u,f;let t;try{t=yield Kr((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new y({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some(g=>g.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==c),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((u=this.cameraTrack)==null?void 0:u.settings.width,(f=this.cameraTrack)==null?void 0:f.settings.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,D)=>g==="imageUrl"?void 0:D))})}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,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var t,r,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((r=this.cameraTrack)==null?void 0:r.settings.width,(o=this.cameraTrack)==null?void 0:o.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)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Kr(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new y({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}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()}createDecodeContext(e){return new _c(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};b([Sa(function(e){this.log.error("update failed",e)})],sn.prototype,"update",1);var XT=0;var gc=class extends H{constructor(e){super("room");d(this,"seq",++XT);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"_isUsingCachedSchedule",!1);d(this,"_log",R.createLogger({id:`r${this.seq}`}));d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,ge(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ge(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ge(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new gp({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Tp({room:this}),this.badCaseDetector=new Ep({room:this}),this.audioManager=new ya(this),this.videoManager=new sn(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return 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(K(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(He(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(qa([a,a]),cr(`https://${a}`)):(o&&cr(o),n&&qa(n))}T.once(I.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:ar.main,sched_back_domain:ar.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 r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return p(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let o=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new y({code:S.INVALID_OPERATION,message:P({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(we.INVALID_DESTROY),new y({code:S.INVALID_OPERATION,message:P({key:L.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(I.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var o,n,a;let r=x();try{let{isCached:c,result:l,detailCost:h}=yield Wl({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Me,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=c,this._log.info(`schedule cache:${+c} ${Tt(l,{keysToExclude:["username","credential"]})}`),c&&T.once(I.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),l),Q((o=l.config)==null?void 0:o.retryCount)&&Pc(l.config.retryCount),K((n=l.config)==null?void 0:n.loggerDomain)&&cr(l.config.loggerDomain),this.videoDecodeFallbackType=((a=l.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,T.emit(I.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),N.addSuccessEvent({key:521700,cost:x()-r,split:50})}catch(c){throw N.addFailedEvent({key:521700,error:c}),c}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var Lp=Be(Qe());var Ru=Be(mu());var Ap=s=>{let i=Ae(s),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var o;if(t.ssrcs&&!E(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function Rp(s){var e;let i=[];for(let t=0;t<s.rtp.length;t++){if(["rtx","red","ulpfec"].includes(s.rtp[t].codec))continue;let r=s.fmtp.filter(o=>o.payload===s.rtp[t].payload)[0];i.push({payload:s.rtp[t].payload,codec:s.rtp[t].codec,fmtp:r?r.config:"",rate:s.rtp[t].rate,rtx:((e=s.rtp[t+1])==null?void 0:e.codec)==="rtx"?s.rtp[t+1].payload:0,rtcpfb:((s==null?void 0:s.rtcpFb)||[]).filter(o=>o.payload===s.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function zT(){return p(this,null,function*(){let s=new RTCPeerConnection;s.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield s.createOffer();if(!i.sdp)return[];let e=Ae(i.sdp),t=Rp(e.media[0]);return s.close(),t})}var Cp=(s,i)=>p(void 0,null,function*(){var c;let e=Ae(s),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};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 r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(l=>({id:l.value,uri:l.uri}))),o.ext&&(t.video.extensions=o.ext.map(l=>({id:l.value,uri:l.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(c=r.rtcpFb)==null||c.forEach(({payload:l,type:h,subtype:u})=>{if(l===n.payload){let f={id:h,params:[]};u&&f.params.push(u),n.rtcpfb.push(f)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...Rp(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield zT()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),yp=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Ae(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:s.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:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:s.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:s.dtls.hash,hash:s.dtls.fingerprint},fmtp:[{payload:s.audio.codecs[0].payload,config:s.audio.codecs[0].fmtp}],icePwd:s.ice.password,iceUfrag:s.ice.ufrag,mid:"0",payloads:String(s.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:m.AUDIO,setup:s.dtls.setup,rtcpFb:s.audio.codecs[0].rtcpfb.map(a=>({payload:s.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:s.audio.codecs[0].payload,codec:s.audio.codecs[0].codec,rate:s.audio.codecs[0].rate,encoding:s.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Cu({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),Rt(o)},Cu=({mid:s,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(s),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:m.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{$r(o,a)})}else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];$r(o,a)}return o},$r=(s,i)=>{s.payloads=`${s.payloads} ${i.payload}`.trim(),s.fmtp.push({payload:i.payload,config:i.fmtp}),s.rtcpFb=[...s.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],s.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(s.payloads=`${s.payloads} ${i.rtx}`,s.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),s.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function QT(s){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"]);s.ext&&(s.ext=s.ext.filter(e=>!i.has(e.uri)))}function YT(s){if(!s.rtcpFb)return;let i=[];s.rtcpFb.forEach((e,t)=>{var r;i.push(e),s.rtcpFb&&((r=s.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),s.rtcpFb=i}function KT(s){s.type===m.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function ZT(s){s.type===m.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var bp=(s,i,e)=>{let t=Ru.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===m.AUDIO||r.type===m.VIDEO)&&(YT(r),KT(r),ZT(r),QT(r),r.type===m.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>$r(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>$r(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),Ru.default.write(t)};var Np=Be(Qe());var Tc=class extends Np.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!he&&Ye&&T.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:o}){if(!(e||t===7||o!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){T.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(Tc,"EVENT_BAD_HEALTH","bad_health");var vp=Tc;function Dp({seiMessageList:s,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(o)}})}function Op(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function Mp(s){let i=[Pi],e=[eu,Kl,Zl,Yl,Dp,Op],t=()=>{let l=[],h=[],u=[];self.onmessage=f=>{f.data.type==="sei"&&(f.data.isMain?(l.push(f.data.data),f.data.small&&u.push(f.data.data)):h.push(f.data.data))},self.onrtctransform=f=>{let{options:g}=f.transformer,D=g.isReceiver?Op(g.userId,g.streamType,g.isAudio):Dp({isAudio:g.isAudio,seiMessageList:g.isMain?g.small?u:l:h,isMain:g.isMain});f.transformer.readable.pipeThrough(D).pipeTo(f.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
|
|
110
|
+
}`});c(this,"yTextureRef");c(this,"uTextureRef");c(this,"vTextureRef");c(this,"Y");c(this,"U");c(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,o=r.createTexture();return r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),o}render(e){let t=this.context.ctx,r=this.width,o=this.height;return this.useProgram(),t.viewport(0,0,r,o),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,o,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var Eu=[s=>{s.codec="avc1.420028"},s=>{delete s.hardwareAcceleration}],fp=(s,i)=>{switch(s){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function VT(s){return s[0]===0&&s[1]===0&&s[2]===0&&s[3]===1}var BT=0,mc=class{constructor(i){c(this,"id",BT++);c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"decoder");c(this,"videoContext");c(this,"gop",0);c(this,"gop_helper",0);c(this,"waitFirstKeyFrame",!0);c(this,"startTimestamp",0);c(this,"startTime",0);c(this,"startPerformanceTime",0);c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"decodeFrameCount",0);c(this,"downgradeLevel",0);c(this,"lastDowngradeTime",0);c(this,"lastFrameDiff",0);c(this,"lastDecodeFrameTimestamp",0);c(this,"config");c(this,"gop_before_configure",[]);c(this,"videoElement");c(this,"type","wasm");c(this,"goodType");c(this,"renderer","2d");c(this,"wasmOption");c(this,"createDecoder");c(this,"_decodeSink");c(this,"isReported",!1);c(this,"track");c(this,"stateChangeOB");c(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=Ye(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=le(e.availableState,B.OFF),this.stopOB=Ye(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),ce(this.stateChangeOB,Dl((r,o)=>(r!==o&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:o}),o),"INITIALIZED"),Pe(this.stopOB),Ie()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ce(this.pipe(this.track),Pe(this.stopOB),Li());ce(e,Ie(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),N.addFailedEvent({key:fp(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),N.addSuccessEvent({key:fp(this.type,this.renderer)}),N.addSuccessEvent({key:514704})})),ce(e,Pi(1),Ie(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!bd()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,d;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!VT(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,o=!1;switch(r){case 5:case 7:o=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),o&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(o)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=L();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(d=i.getMetadata)==null?void 0:d.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>f(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:o,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":for(let d=0;d<=Eu.length;d++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(d===Eu.length){e.error(3);return}Eu[d](this.config)}t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",d=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${d.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(d.timestamp)),e.next(d)}),t.on("error",d=>{i.log.error(d),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&o==="webgl"){this.videoContext=new Ne({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Ne.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let d=new hc(this.videoContext);t.on("videoCodecInfo",l=>d.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:d.Y,u:d.U,v:d.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&d.render(this.decodedFrameCount):d.render(this.decodedFrameCount)}),i.source=d,i.player.setCanvas(this.videoContext._canvas,2)}else if(o==="videoFrame"){i.player.setCanvas();let d=new MediaStreamTrackGenerator({kind:"video"}),l=d.writable.getWriter();i.setInputMediaStreamTrack(d),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new Ge({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let d=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{d.image=u,d.update()}catch(h){delete this.goodType,i.log.error(h),e.error(11)}});let l=new Mr(this.videoContext,{name:"remotePlayer",logger:i.log});d.connect(l),i.source=d,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var tn=class extends _p.EventEmitter{constructor(e){super();this.room=e;c(this,"videoContext");c(this,"_glVideoContext");c(this,"_2dVideoContext");c(this,"destination");c(this,"smallVideoContext");c(this,"smallDestination");c(this,"smallTrackSource");c(this,"smallImageSource");c(this,"_isMirror",!1);c(this,"cameraTrack");c(this,"cameraNode");c(this,"mirrorNode");c(this,"mixNode");c(this,"screenTrack");c(this,"screenNode");c(this,"selfModel",!1);c(this,"blurRadius",3);c(this,"arTrack");c(this,"Wasm");c(this,"waterMarkNode");c(this,"_waterMarkOption");c(this,"watermarkImageList",[]);c(this,"_beautyParams");c(this,"isUsingArTrack",!1);c(this,"_isMixScreen",!1);c(this,"_virtualBackground");c(this,"_virtualBackgroundAbortCallback");c(this,"virtualBackgroundInstance");c(this,"_bgAssetPath");c(this,"log",C.createLogger({id:"vm"}));c(this,"_checkId",0);c(this,"_use2d",!1);c(this,"_autoSwitchRenderMode",!0);c(this,"_selfieSegmentation");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ge({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 Ge({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ne({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(Ne.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{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(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(ji||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?N.addFailedEvent({key:r,error:t}):N.addSuccessEvent({key:r})}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{if(this._glVideoContext=new Ne({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}setSmallVideo(e,t){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Fa(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Ne.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:o}=this.cameraTrack.settings;this.smallTrackSource.resize(r,o),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:o,player:n}=r;this.setSmallVideo(o,e),ji&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${a?a.label:"no output track"}`),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return f(this,null,function*(){var o,n,a;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),dt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof wi?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof wi?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Ba(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new uc(this.videoContext,{input:this.initialTrack,width:t.width,height:t.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let d=this.cameraNode;d.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new dc(this.videoContext,this.log)),d=d.connect(this.mirrorNode),d.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new lc(this.videoContext,this.log),d.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption?(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y):(o=this.waterMarkNode)==null||o.resize(t.width,t.height),(n=this.waterMarkNode)==null||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(a=this.screenNode)==null||a.connect(this.mixNode,{zIndex:0}),d=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),d.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof nt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof He)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof ai){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof nt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof He?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ai&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(this,null,function*(){this.cameraTrack=e,this.update(!0)})}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 f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let o=r.getContext("2d");if(!o)throw new b({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:d,width:l,height:u})=>{o.drawImage(n,a,d,l,u)}),Qr(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){var h,m;let t;try{t=yield Qr((e==null?void 0:e.imageElement)||e.imageUrl)}catch(_){throw new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:d="watermark",zIndex:l=2}=e;this.watermarkImageList.some(_=>_.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(_=>_.type!==d),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((h=this.cameraTrack)==null?void 0:h.settings.width,(m=this.cameraTrack)==null?void 0:m.settings.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(_,I)=>_==="imageUrl"?void 0:I))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var t,r,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((r=this.cameraTrack)==null?void 0:r.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return f(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Qr(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new b({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}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 f(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new mc(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};y([Ea(function(e){this.log.error("update failed",e)})],tn.prototype,"update",1);var FT=0;var pc=class extends B{constructor(e){super("room");c(this,"seq",++FT);c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"privateMapKey");c(this,"latencyLevel");c(this,"tinyId");c(this,"scene");c(this,"roomId");c(this,"useStringRoomId");c(this,"role","anchor");c(this,"joinParams",null);c(this,"localTracks",new Set);c(this,"enableAutoPlayDialog",!0);c(this,"autoReceiveAudio",!0);c(this,"autoReceiveVideo",!0);c(this,"proxy_ws");c(this,"proxy_wt");c(this,"proxy_unified");c(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}});c(this,"keyPointManager");c(this,"audioManager");c(this,"videoManager");c(this,"callDurationCalculator");c(this,"badCaseDetector");c(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});c(this,"videoDecodeFallbackType");c(this,"_isUsingCachedSchedule",!1);c(this,"_log",C.createLogger({id:`r${this.seq}`}));c(this,"_joinedTimestamp",0);c(this,"_sdkType");c(this,"heartbeatReport");c(this,"quality");c(this,"enableSEI");c(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,fe(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),fe(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),fe(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new hp({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new mp({room:this}),this.badCaseDetector=new pp({room:this}),this.audioManager=new Ra(this),this.videoManager=new tn(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(K(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(tt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(Ja([a,a]),or(`https://${a}`)):(o&&or(o),n&&Ja(n))}E.once(T.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:sr.main,sched_back_domain:sr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let o=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:S.INVALID_OPERATION,message:U({key:x.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Me.INVALID_DESTROY),new b({code:S.INVALID_OPERATION,message:U({key:x.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,E.emit(T.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var o,n,a;let r=L();try{let{isCached:d,result:l,detailCost:u}=yield $l({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ve,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=d,this._log.info(`schedule cache:${+d} ${_t(l,{keysToExclude:["username","credential"]})}`),d&&E.once(T.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),l),Q((o=l.config)==null?void 0:o.retryCount)&&kc(l.config.retryCount),K((n=l.config)==null?void 0:n.loggerDomain)&&or(l.config.loggerDomain),this.videoDecodeFallbackType=((a=l.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,E.emit(T.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:u}),N.addSuccessEvent({key:521700,cost:L()-r,split:50})}catch(d){throw N.addFailedEvent({key:521700,error:d}),d}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var vp=Ue(qe());var Su=Ue(lu());var gp=s=>{let i=Ee(s),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var o;if(t.ssrcs&&!g(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(d=>d.attribute==="cname")[1])==null?void 0:o.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function Tp(s){var e;let i=[];for(let t=0;t<s.rtp.length;t++){if(["rtx","red","ulpfec"].includes(s.rtp[t].codec))continue;let r=s.fmtp.filter(o=>o.payload===s.rtp[t].payload)[0];i.push({payload:s.rtp[t].payload,codec:s.rtp[t].codec,fmtp:r?r.config:"",rate:s.rtp[t].rate,rtx:((e=s.rtp[t+1])==null?void 0:e.codec)==="rtx"?s.rtp[t+1].payload:0,rtcpfb:((s==null?void 0:s.rtcpFb)||[]).filter(o=>o.payload===s.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function $T(){return f(this,null,function*(){let s=new RTCPeerConnection;s.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield s.createOffer();if(!i.sdp)return[];let e=Ee(i.sdp),t=Tp(e.media[0]);return s.close(),t})}var Ep=(s,i)=>f(void 0,null,function*(){var d;let e=Ee(s),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};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 r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(l=>({id:l.value,uri:l.uri}))),o.ext&&(t.video.extensions=o.ext.map(l=>({id:l.value,uri:l.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(d=r.rtcpFb)==null||d.forEach(({payload:l,type:u,subtype:h})=>{if(l===n.payload){let m={id:u,params:[]};h&&m.params.push(h),n.rtcpfb.push(m)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...Tp(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield $T()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),Sp=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Ee(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:s.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:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:s.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:s.dtls.hash,hash:s.dtls.fingerprint},fmtp:[{payload:s.audio.codecs[0].payload,config:s.audio.codecs[0].fmtp}],icePwd:s.ice.password,iceUfrag:s.ice.ufrag,mid:"0",payloads:String(s.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:p.AUDIO,setup:s.dtls.setup,rtcpFb:s.audio.codecs[0].rtcpfb.map(a=>({payload:s.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:s.audio.codecs[0].payload,codec:s.audio.codecs[0].codec,rate:s.audio.codecs[0].rate,encoding:s.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Iu({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),It(o)},Iu=({mid:s,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(s),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:p.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Br(o,a)})}else{let n=i.video.codecs.findIndex(d=>d.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];Br(o,a)}return o},Br=(s,i)=>{s.payloads=`${s.payloads} ${i.payload}`.trim(),s.fmtp.push({payload:i.payload,config:i.fmtp}),s.rtcpFb=[...s.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],s.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(s.payloads=`${s.payloads} ${i.rtx}`,s.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),s.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function HT(s){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"]);s.ext&&(s.ext=s.ext.filter(e=>!i.has(e.uri)))}function GT(s){if(!s.rtcpFb)return;let i=[];s.rtcpFb.forEach((e,t)=>{var r;i.push(e),s.rtcpFb&&((r=s.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),s.rtcpFb=i}function WT(s){s.type===p.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function JT(s){s.type===p.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Ip=(s,i,e)=>{let t=Su.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===p.AUDIO||r.type===p.VIDEO)&&(GT(r),WT(r),JT(r),HT(r),r.type===p.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Br(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(d=>Br(r,d))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),Su.default.write(t)};var Ap=Ue(qe());var fc=class extends Ap.EventEmitter{constructor(e){super();this.room=e;c(this,"mainFpsHealth",1);c(this,"mainBitrateHealth",1);c(this,"badMainBitrateHealthCount",0);c(this,"lastEmitBadHealthTime",0);c(this,"log");!ue&&Xe&&E.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:o}){if(!(e||t===7||o!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){E.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};c(fc,"EVENT_BAD_HEALTH","bad_health");var Cp=fc;function Rp({seiMessageList:s,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(o)}})}function yp(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(d=>{self.postMessage({type:"sei",seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function bp(s){let i=[ki],e=[Yl,zl,Ql,Xl,Rp,yp],t=()=>{let l=[],u=[],h=[];self.onmessage=m=>{m.data.type==="sei"&&(m.data.isMain?(l.push(m.data.data),m.data.small&&h.push(m.data.data)):u.push(m.data.data))},self.onrtctransform=m=>{let{options:_}=m.transformer,I=_.isReceiver?yp(_.userId,_.streamType,_.isAudio):Rp({isAudio:_.isAudio,seiMessageList:_.isMain?_.small?h:l:u,isMain:_.isMain});m.transformer.readable.pipeThrough(I).pipeTo(m.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
|
|
111
111
|
const videoDecodePipeline=[${s.videoDecodePipeline.toString()}];
|
|
112
112
|
const audioEncodePipeline = [${s.audioEncodePipeline.toString()}];
|
|
113
113
|
const audioDecodePipeline = [${s.audioDecodePipeline.toString()}];`,o=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
|
|
114
114
|
`)}
|
|
115
115
|
${e.map(l=>l.toString()).join(`
|
|
116
|
-
`)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),
|
|
117
|
-
offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return p(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return p(this,null,function*(){var r,o,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=x(),c={type:"answer",sdp:yp({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(c),yield this.waitForPeerConnectionConnected();let l=((o=this._room.scheduleResult.config)==null?void 0:o.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||N.addSuccessEvent({key:521703,cost:x()-a})}catch(a){let c=a instanceof y&&a.code===S.API_CALL_ABORTED;throw c||this._log.error(`connect failed: ${a}`,e),this.reset(),!c&&!this.isReconnecting&&(N.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}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(ye.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=v({ability:t},e),o=yield this._signalChannel.sendWaitForResponse({command:Y.REBUILD_PEER_CONNECTION,responseCommand:G.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(o.data.code!==0)throw new y({code:o.data.code,message:o.data.message});yield this.connect(o.data.data.ability,!0),N.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(I.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=vt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ii(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),N.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=gi()&&this._log.warn(`SDK has tried reconnect for ${gi()} 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.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(ye.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===me.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var o;let t=((o=this._peerConnection)==null?void 0:o.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===me.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===me.FAILED||e.target.connectionState===me.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===me.CONNECTED||e.target.connectionState===me.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(I.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 yt;let e=null;return!Zi()||this._peerConnection.getSenders().length===0?yt:(e=this._peerConnection.getSenders()[0].transport,!Rr()||this._peerConnection.getReceivers().length===0?yt:e?e.state:yt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(mi.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,r]of e)if(Ki(r)){let o=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&In(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(I.LEAVE_SUCCESS,o,this),this.off(mi.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Pp+=1,tE(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),wp=!0,this.emit(mi.FIREWALL_RESTRICTION)),t(c)},Xs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},T.on(I.LEAVE_SUCCESS,o,this),this.on(mi.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return p(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(f=>f.direction==="inactive").slice(0,3).map(f=>(f.direction=m.TRANSCEIVER_DIRECTION_RECVONLY,Number(f.mid)));this._parsedAnswer||(this._parsedAnswer=Ae(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(f=>{var g;return(g=f.ssrcs)==null?void 0:g.find(D=>{var _;return(_=D.value)==null?void 0:_.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[0])),c=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[1])),l=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let f=Cu({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ae(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(f)),l=JSON.parse(JSON.stringify(f)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${h}`},{id:e.audio,attribute:"msid",value:`${h}-${m.MAIN} ${h}-audio`}],c.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${h}`},{id:e.video,attribute:"msid",value:`${h}-${m.MAIN} ${h}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${h}`},{id:e.videoRtx,attribute:"msid",value:`${h}-${m.MAIN} ${h}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${h}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:u},{id:e.auxiliary,attribute:"msid",value:`${u} ${h}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${u} ${h}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${u} ${h}-aux${m.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(f=>f.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.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),r=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ae(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(yo()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let h=a[l],u;l===0&&t?u=t:l===1&&r?u=r:l===2&&o?u=o:l===3&&n&&(u=n),u&&(yield this.setSenderMaxBitrate(h,u))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||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 r,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=Ae(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();return(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited"?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=t*1e3,e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=Ae(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ae(this._peerConnection.remoteDescription.sdp));let a=oe?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:oe?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:oe?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:oe?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:oe?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:oe?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:oe?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:oe?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:oe?o*1e3:o}]);let c={type:"offer",sdp:Rt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(E(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}setDegradationPreference(e,t,r){if(Ye&<<83||Se&&td(Xt,"12.1")||oe&&io<138)return;let o=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),o.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),o.degradationPreference=n,e.setParameters(o).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=Rt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>p(this,null,function*(){var n,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,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
116
|
+
`)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),d=new Worker(a);return URL.revokeObjectURL(a),d}var di=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(di||{}),Dp=0,Op=!1,jT=new Set,qT=s=>Dp>2&&!Op&&jT.size===0&&s,XT=1,Ut=class extends vp.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();c(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});c(this,"currentState","DISCONNECTED");c(this,"_room");c(this,"_signalChannel");c(this,"_peerConnection",null);c(this,"_datachannel",null);c(this,"_enableCustomMessage");c(this,"_log");c(this,"_downlinkMIDMap",new Map);c(this,"_downlinkMIDUserIDMap",new Map);c(this,"_reconnectionTimer",-1);c(this,"reconnectionCount",0);c(this,"clientAbility");c(this,"_serverAbility",null);c(this,"addDownlinkQueue",new Set);c(this,"removeDownlinkQueue",new Set);c(this,"_parsedAnswer",null);c(this,"_updateSDPPromise",null);c(this,"_waitForPCConnectedPromise");c(this,"clearConnectTimeout");c(this,"_isSDPLogged",!1);c(this,"enableInsertableStreams",!1);c(this,"insertableStreamsAbortMap",new Map);c(this,"receiverRemoteTrackMap",new WeakMap);c(this,"scriptTransformWorker");c(this,"_isRelayTried",!1);c(this,"_rttOverCount",0);c(this,"originOffer",null);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=C.createLogger({id:`spc${XT++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Ni?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}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}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,r;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?gp(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){this.useHWEncoder(!1,e?7:2)}initScriptTransformWorker(){sa&&(this.scriptTransformWorker=bp({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"&&this.emit("sei-message",e.data),e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}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}getPeerConnectionConfig(e){var o;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(o=this._peerConnection)==null?void 0:o.getConfiguration().encodedInsertableStreams;return Nn(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return f(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let o=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${o}`),o==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():o==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),N.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):o==="failed"&&N.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let o=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[o==="closed"?"debug":"info"](`signaling state: ${o}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=o=>this.emit("track",o),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=o=>{let n=new Cu(o.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=o=>{this._log.warn("datachannel error",o)}),this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield Ep(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:o}=this;o&&(this._log.debug(`dtls state: ${o.state}`),o.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():o.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),N.addSuccessEvent({key:521707}),this.clientAbility}catch(o){throw N.addFailedEvent({key:521707,error:o}),this._log.error(`initialize failed ${o}
|
|
117
|
+
offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return f(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,o,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=L(),d={type:"answer",sdp:Sp({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(d),yield this.waitForPeerConnectionConnected();let l=((o=this._room.scheduleResult.config)==null?void 0:o.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||N.addSuccessEvent({key:521703,cost:L()-a})}catch(a){let d=a instanceof b&&a.code===S.API_CALL_ABORTED;throw d||this._log.error(`connect failed: ${a}`,e),this.reset(),!d&&!this.isReconnecting&&(N.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return f(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(Ae.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=v({ability:t},e),o=yield this._signalChannel.sendWaitForResponse({command:X.REBUILD_PEER_CONNECTION,responseCommand:F.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(o.data.code!==0)throw new b({code:o.data.code,message:o.data.message});yield this.connect(o.data.data.ability,!0),N.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),E.emit(T.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=yt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield gi(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),N.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=mi()&&this._log.warn(`SDK has tried reconnect for ${mi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ae.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===he.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var o;let t=((o=this._peerConnection)==null?void 0:o.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===he.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===he.FAILED||e.target.connectionState===he.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===he.CONNECTED||e.target.connectionState===he.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),E.emit(T.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 Ct;let e=null;return!Qi()||this._peerConnection.getSenders().length===0?Ct:(e=this._peerConnection.getSenders()[0].transport,!Ir()||this._peerConnection.getReceivers().length===0?Ct:e?e.state:Ct)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(di.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(zi(r)){let o=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Sn(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=d=>{d.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:d})=>{d===this._room&&(clearTimeout(a),n(),t(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{E.off(T.LEAVE_SUCCESS,o,this),this.off(di.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let d=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Dp+=1,qT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Op=!0,this.emit(di.FIREWALL_RESTRICTION)),t(d)},js);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},E.on(T.LEAVE_SUCCESS,o,this),this.on(di.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){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(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=p.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=Ee(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var _;return(_=m.ssrcs)==null?void 0:_.find(I=>{var R;return(R=I.value)==null?void 0:R.includes(r)})}),a,d,l;if(n.length===3)a=n[0],d=n[1],l=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[0])),d=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[1])),l=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=Iu({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ee(this._peerConnection.localDescription.sdp),isDownlink:!0});d=JSON.parse(JSON.stringify(m)),l=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${p.MAIN} ${u}-audio`}],d.direction=p.TRANSCEIVER_DIRECTION_SENDONLY,d.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:h},{id:e.auxiliary,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,d.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return f(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),r=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ee(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(Co()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],h;l===0&&t?h=t:l===1&&r?h=r:l===2&&o?h=o:l===3&&n&&(h=n),h&&(yield this.setSenderMaxBitrate(u,h))}let d=!1;r&&a[1].track&&(d=this.setStartBitrate(1,r)),n&&a[3].track&&(d=this.setStartBitrate(3,n)||d),d&&(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 r,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=Ee(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();return(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited"?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=t*1e3,e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=Ee(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ee(this._peerConnection.remoteDescription.sdp));let a=se?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:se?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:se?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}]);let d={type:"offer",sdp:It(n)};return this.updateSDP({localDescription:d})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(g(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}setDegradationPreference(e,t,r){if(Xe&&ct<83||ge&&Kc(jt,"12.1")||se&&eo<138)return;let o=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),o.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),o.degradationPreference=n,e.setParameters(o).catch(d=>this._log.warn(`${a} failed: ${d}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=It(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>f(this,null,function*(){var n,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,r()}catch(d){this._log.error(d),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
118
118
|
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)}
|
|
119
|
-
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:l,currentDirection:h,direction:u,stopped:f})=>({mid:l,currentDirection:h,direction:u,stopped:f})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return p(this,null,function*(){if(!oe||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===Z.INACTIVE&&n===Z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Z.SENDONLY&&n===Z.INACTIVE&&(this._parsedAnswer.media[o].direction=Z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Ae(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=bp(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===m.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],$r(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];E(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===m.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],$r(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Jt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var h;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),l=(this._isRelayTried||c>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return p(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),N.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};b([Ra("reconnect")],Ft.prototype,"startReconnection",1),b([Li(e=>e.userId)],Ft.prototype,"addDownlink",1),b([Li(e=>e)],Ft.prototype,"removeDownlink",1),b([ni(!0)],Ft.prototype,"updateSDP",1),b([at(521712,!1)],Ft.prototype,"setOffer",1),b([at(521713,!1)],Ft.prototype,"setAnswer",1);var yu=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},bu=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new yu(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},kp=new Set;function Hr(){let s=Math.floor(Math.random()*4294967296);return kp.has(s)?Hr():(kp.add(s),s)}var xp=Be(Qe());var Gr=class extends xp.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(T.emit(I.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 on=class extends Gr{constructor(e){super(w(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}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:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||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:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${bi()} ${Tr()}`),N.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Zt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=v({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&Ji),bigVideo:!!(this.flag&Wi),smallVideo:!!(this.flag&js),auxVideo:!!(this.flag&dr)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,h,u,f,g,D,_;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),he&&cs()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(gt["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:G.SPC_PUBLISH_RESULT,data:w(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:C}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],C,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(g=(f=this.localMainVideoTrack)==null?void 0:f.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],h=[],u=(g,D,_)=>{var M,ne;let C=c[D].sender.replaceTrack(_);h.push(D),(M=this.singlePC)!=null&&M.enableInsertableStreams&&C.then(()=>this.createEncodedStreams(c[D].sender,g)),(ne=this.singlePC)!=null&&ne.scriptTransformWorker&&this.initSenderTransfrom(c[D].sender,g),l.push(C)};a&&u(e.mediaType,0,a),n&&u(t.mediaType,o?3:1,n),r&&u(8,2,r);let f=this.singlePC.setTransceiverDirection(Z.SENDONLY,h);return l.push(f),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,h)=>{var f;let u=this.getTrackByMediaType(t);h.enqueue((f=this.singlePC)!=null&&f.isUsingH264&&u?u.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return p(this,null,function*(){var r;if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:o}=t[2];(r=this.singlePC)!=null&&r.enableInsertableStreams&&this.createEncodedStreams(o,8),yield o.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Z.SENDONLY,[2])}}else yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Z.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(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},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=w(v({},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.singlePC.setTransceiverDirection(Z.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.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),ei){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.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?m.AUXILIARY:m.MAIN} stream`),Zt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?m.AUXILIARY:m.MAIN} stream`),Zt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?m.AUXILIARY:m.MAIN} stream`),r.kind===m.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===m.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===m.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:G.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(I.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===lr?(this._log.error(we.NOT_SUPPORTED_H264ENCODE),new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})})):new y({code:S.UNKNOWN,message:P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.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}))})}};b([Ze(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],on.prototype,"publish",1),b([Ze(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],on.prototype,"unpublish",1);var Nu=on;function Up(s){return Object.keys(s).filter(i=>s[i])}var Us=class extends Gr{constructor(e){super(w(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new wi(this._room,this),this.remoteVideoTrack=new ui(this._room,this),this.remoteAuxiliaryTrack=new bs(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}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 Si(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var h,u;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=m.AUDIO;r.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let l=this.remoteAudioTrack;c===m.VIDEO?l=this.remoteVideoTrack:c===m.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(h=this.singlePC)==null||h.receiverRemoteTrackMap.set(o,l),(u=this.singlePC)!=null&&u.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===m.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return p(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Up(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ye&<<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Up(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:P({key:L.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(){return p(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}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){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Hr(),bigVideoSsrc:Hr(),bigVideoRtxSsrc:Hr(),auxVideoSsrc:Hr(),auxVideoRtxSsrc:Hr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:G.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:r},retries:3,retryTimeout:0});if(h.data.code!==0)throw new y({code:h.data.code,message:h.data.message})}catch(h){throw yield this.removeDownlink(),h}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!na)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(Q(n)||Q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return p(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!na||!this.singlePC||!this._peerConnection||Ri(e)&&Ri(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Ri(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var u;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Ri(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Ri(t)||!c&&Ri(e))return;let l=c?t||0:e,h=(a.jitterBufferTarget||0)+100;h>l||(a.jitterBufferTarget=h,this._log.debug(`set ${c?"aux ":""}${(u=a==null?void 0:a.track)==null?void 0:u.kind} jitterBuffer delay ${h} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};b([ni(),z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Us.prototype,"subscribe",1),b([ni()],Us.prototype,"unsubscribe",1),b([Li(()=>"jitter")],Us.prototype,"setJitterBufferDelay",1);var Vp=Us;function Bp(){return z(s=>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=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Fp(){return z(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var $p=Be(Qe());function rE(){return Math.floor(Math.random()*16383)}var Sc=class Sc extends $p.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(G.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||rE(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>Sc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Ii(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,h)=>l.message.seq-h.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(Sc,"SEQ_INTERVAL",300);var Ec=Sc;var{isString:Hp,isUndefined:Vs,getNetworkType:sE,isEmpty:nn}=dt,$t=class extends gc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",ps);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new tn(this,this._log),this.userManager=new Ga(this.userId,this._log),this._version=Me,this.sdpSemantics=Jr,Vs(e.sdpSemantics)?ti.isUnifiedPlanDefault()&&(this.sdpSemantics=ji):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${sE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Vs(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&ps,!Vs(e.enableSPC)&&ps&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new vp(this)}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.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Mu(n,[]);T.emit(I.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},o))}),this.joinParams=e,new Promise((o,n)=>p(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(h){if(h instanceof y&&h.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let l=x();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),N.addSuccessEvent({key:521708,cost:x()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){N.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Ft({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>p(this,null,function*(){var c,l,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(ye.SETUP_FAILED,u=>{this.clearJoinTimeout(),T.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),o(u)}),ge((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&ps&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:ad(),netType:mr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(h=this.scheduleResult.config)!=null&&h.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:S.JOIN_ROOM_FAILED,message:P({key:L.JOIN_ROOM_TIMEOUT})}))},a),T.emit(I.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(G.JOIN_ROOM_RESULT,u=>p(this,null,function*(){this.clearJoinTimeout();let{code:f,message:g,data:D,tinyId:_}=u.data;T.emit(I.JOIN_RECEIVED_CMD_RES,{room:this,code:f}),f===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var C;(C=this.singlePC)==null||C.connect(w(v({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${f} error: ${g}`),o(new y({code:S.JOIN_ROOM_FAILED,extraCode:f,message:P({key:L.JOIN_ROOM_FAILED,data:{error:g,code:f}})})))}))}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(w(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),te.logSuccessEvent({userId:this.userId,eventType:rt.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(mi.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Nu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(mi.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof en&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),te.logFailedEvent({userId:this.userId,eventType:rt.REJOIN,error:e}),this.emit("error",new y({code:S.JOIN_ROOM_FAILED,message:P({key:L.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||tp(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new ks({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Ec(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new xs({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(xs.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Ge(this,this.signalChannel).add(ye.CONNECTION_STATE_CHANGED,a=>{T.emit(I.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(ye.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(G.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:h}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:h})}).add(G.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(G.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(G.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(te.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}),this.signalChannel.once(ye.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(I.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&T.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||be(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(I.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Sm(this.userId):[],o=w(v({str_sdk_version:Gs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:mr()},t.msg_device_info)});if(this.heartbeatReport=o,T.emit(I.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",w(v({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Oc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),T.emit(I.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 instanceof en&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?Vp:_u)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",w(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.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:Y.GET_USER_LIST,responseCommand:G.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!lu)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)===me.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof it&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===me.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.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,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new en({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),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()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new _u({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(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.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 y({code:S.INVALID_OPERATION,message:P({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}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:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:G.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new y({code:S.SWITCH_ROLE_FAILED,message:P({key:L.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new y({code:S.SWITCH_ROLE_FAILED,message:P({key:L.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return p(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof St&&(c instanceof ci?r.audio=c:t.audio=c),c instanceof Je&&(c instanceof ct&&c.mediaType===2?r.video=c:t.video=c)});let o=nn(t),n=nn(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Nu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new en({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",w(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==S.ICE_TRANSPORT_ERROR&&(l===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.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={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof St&&(o instanceof ci?r.audio=o:t.audio=o),o instanceof Je&&(o instanceof ct&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");nn(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),nn(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}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||!Od()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(I.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:m.VIDEO,videoType:m.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),T.emit(I.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${dc(n)}] prev: [${dc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(I.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():S.UNKNOWN,c=n;throw n instanceof y?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:S.API_CALL_ABORTED,message:P({key:L.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:P({key:L.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),T.emit(I.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(I.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var o;br.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!br.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return p(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!Md||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;Q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return p(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return p(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},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 r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(dt.getTurnServer(o))):dt.isPlainObject(e)&&r.push(dt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.START_PUBLISH_TENCENT_CDN_RES:G.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.STOP_PUBLISH_TENCENT_CDN_RES:G.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:G.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dt.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):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,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:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&h.smallVideo&&(h.video=!0,h.smallVideo=!1),h.smallVideo===t.smallVideo&&h.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(h,"main"),e.remoteVideoTrack.setMediaType(h.smallVideo?8:4),this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video successfully. count ${jr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=jr}catch(u){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${jr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:jr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`);let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Hp(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Vs(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:S.INVALID_PARAMETER,message:P({key:L.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(!Vs(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Vs(e.userDefinePushArgs))if(Hp(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 y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_USER_DEFINE_PUSH_ARGS})});nn(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return p(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Oi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}};b([pe(["left",H.INIT],"joined"),ot({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Vt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),Qm()],$t.prototype,"join",1),b([pe("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Ym(),Ra("leave room"),ko({fnName:"publish",validateArgs:!1}),ko({fnName:"unsubscribe",validateArgs:!1})],$t.prototype,"leave",1),b([ni(),Bp(),ot({settings:{retries:gi,timeout:e=>vt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),T.emit(I.PUBLISH_FAILED,{room:this}))}})],$t.prototype,"publish",1),b([ko({fnName:"publish"}),nm("api-call"),ni(),Fp(),Ze(function(){var e,t;this.localTracks.size===0&&Zi()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],$t.prototype,"unpublish",1),b([Sa(e=>{if(e.code!==S.API_CALL_ABORTED)throw e}),Li(e=>e.userId)],$t.prototype,"replaceTrack",1),b([Li((...e)=>e[0].userId),ba(),Km(),ot({settings:{retries:gi,timeout:e=>vt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),T.emit(I.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],$t.prototype,"subscribe",1),b([ko({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),Li((...e)=>e[0].userId)],$t.prototype,"unsubscribe",1);Ko.create=Ko._create.bind(Ko,$t);var k1=Ko;export{k1 as default};
|
|
119
|
+
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:l,currentDirection:u,direction:h,stopped:m})=>({mid:l,currentDirection:u,direction:h,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(d)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!se||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===Y.INACTIVE&&n===Y.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Y.SENDONLY&&n===Y.INACTIVE&&(this._parsedAnswer.media[o].direction=Y.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Ee(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=Ip(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Br(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];g(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===p.VIDEO){let d;e&&this.is42001fSupported?d=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(d=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),d&&!((a=n.payloads)!=null&&a.includes(String(d.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Br(n,d),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Gt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let d=Math.floor(o/r),l=(this._isRelayTried||d>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${d} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),N.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};y([Aa("reconnect")],Ut.prototype,"startReconnection",1),y([Oi(e=>e.userId)],Ut.prototype,"addDownlink",1),y([Oi(e=>e)],Ut.prototype,"removeDownlink",1),y([ii(!0)],Ut.prototype,"updateSDP",1),y([ot(521712,!1)],Ut.prototype,"setOffer",1),y([ot(521713,!1)],Ut.prototype,"setAnswer",1);var Au=class{constructor(i){c(this,"tag");c(this,"len");c(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Cu=class{constructor(i){c(this,"tinyId");c(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Au(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Np=new Set;function Fr(){let s=Math.floor(Math.random()*4294967296);return Np.has(s)?Fr():(Np.add(s),s)}var kp=Ue(qe());var $r=class extends kp.default{constructor(e){super();c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_currentState","DISCONNECTED");c(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=C.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(E.emit(T.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 rn=class extends $r{constructor(e){super(M(v({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(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});c(this,"_flag",0);c(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}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:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:d}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:d||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:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Ai()} ${fr()}`),N.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(zt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=v({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&Hi),bigVideo:!!(this.flag&$i),smallVideo:!!(this.flag&Ws),auxVideo:!!(this.flag&nr)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,m,_,I,R;if(!this.singlePC)return;this.installEvents(),yield Promise.all([this.singlePC.waitForPeerConnectionConnected(),this.singlePC.waitForReconnected()]);let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),ue&&ns()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(ft["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let d;if(t&&!r&&t.small&&(d=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:X.SPC_PUBLISH,responseCommand:F.SPC_PUBLISH_RESULT,data:M(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:d,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:D}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],D,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(_=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(R=this._room.scheduleResult.config)!=null&&R.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!ut())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,d=this._peerConnection.getTransceivers(),l=[],u=[],h=(_,I,R)=>{var W,te;let D=d[I].sender.replaceTrack(R);u.push(I),(W=this.singlePC)!=null&&W.enableInsertableStreams&&D.then(()=>this.createEncodedStreams(d[I].sender,_)),(te=this.singlePC)!=null&&te.scriptTransformWorker&&this.initSenderTransfrom(d[I].sender,_),l.push(D)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,o?3:1,n),r&&h(8,2,r);let m=this.singlePC.setTransceiverDirection(Y.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,d;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((d=this.getTrackByMediaType(t))!=null&&d.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m;let h=this.getTrackByMediaType(t);u.enqueue((m=this.singlePC)!=null&&m.isUsingH264&&h?h.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){var r;if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:o}=t[2];(r=this.singlePC)!=null&&r.enableInsertableStreams&&this.createEncodedStreams(o,8),yield o.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Y.SENDONLY,[2])}}else yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Y.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(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l,u;yield Promise.all([(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected(),(u=this.singlePC)==null?void 0:u.waitForReconnected()]);let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=M(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=M(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(Y.INACTIVE,d),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 f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:X.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:X.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),Qt){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.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:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(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?p.AUXILIARY:p.MAIN} stream`),zt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Y.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Y.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(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?p.AUXILIARY:p.MAIN} stream`),zt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Y.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}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:F.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(T.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===ar?(this._log.error(Me.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:U({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(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}))})}};y([Qe(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],rn.prototype,"publish",1),y([Qe(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],rn.prototype,"unpublish",1);var Ru=rn;function Mp(s){return Object.keys(s).filter(i=>s[i])}var ws=class extends $r{constructor(e){super(M(v({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});c(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Mi(this._room,this),this.remoteVideoTrack=new ai(this._room,this),this.remoteAuxiliaryTrack=new Rs(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}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,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let d=p.AUDIO;r.kind===p.VIDEO&&(d=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;d===p.VIDEO?l=this.remoteVideoTrack:d===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var d,l;let a=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let d=o.enqueue(n);d&&a.enqueue(d)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Mp(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Xe&&ct<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(d=>d===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Mp(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=X.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=X.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let d=new b({code:a.code,message:U({key:x.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}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(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Fr(),bigVideoSsrc:Fr(),bigVideoRtxSsrc:Fr(),auxVideoSsrc:Fr(),auxVideoRtxSsrc:Fr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:d,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:d,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:X.SPC_SUBSCRIBE,responseCommand:F.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:r},retries:3,retryTimeout:0});if(u.data.code!==0)throw new b({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!oa)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(Q(n)||Q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!oa||!this.singlePC||!this._peerConnection||Ei(e)&&Ei(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Ei(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var h;let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Ei(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(d&&Ei(t)||!d&&Ei(e))return;let l=d?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${d?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};y([ii(),q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],ws.prototype,"subscribe",1),y([ii()],ws.prototype,"unsubscribe",1),y([Oi(()=>"jitter")],ws.prototype,"setJitterBufferDelay",1);var Lp=ws;function Pp(){return q(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function wp(){return q(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var xp=Ue(qe());function zT(){return Math.floor(Math.random()*16383)}var gc=class gc extends xp.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;c(this,"log");c(this,"cmdIdSeqMap",new Map);c(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(F.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||zT(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(X.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>gc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let d=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:d})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),gi(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let d=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);d[0]&&(o=d[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};c(gc,"SEQ_INTERVAL",300);var _c=gc;var{isString:Up,isUndefined:xs,getNetworkType:QT,isEmpty:sn}=at,Vt=class extends pc{constructor(e){super(e);c(this,"_businessInfo");c(this,"userManager");c(this,"_version");c(this,"_heartbeat",-1);c(this,"_lastHeartBeatTime",-1);c(this,"_stats");c(this,"_joinTimeout",-1);c(this,"_firstPublishedList",null);c(this,"_joinReject",null);c(this,"_isRelayChanged",!1);c(this,"sdpSemantics");c(this,"signalChannel",null);c(this,"uplinkConnection",null);c(this,"singlePC",null);c(this,"enableSPC",hs);c(this,"_changeBigSmallRecords",new Map);c(this,"networkQuality");c(this,"_iceTransportPolicy");c(this,"forceRelay",!1);c(this,"_turnServers",[]);c(this,"_iceServersFromJoin");c(this,"_syncUserListInterval",-1);c(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});c(this,"enableSEI",!1);c(this,"_enableAudioVolumeEvaluation",!1);c(this,"_audioVolumeIntervalId",0);c(this,"_enableMultiAuxStream",!1);c(this,"_pureAudioPushMode",!1);c(this,"_customMessageManager");c(this,"preferHW",!1);c(this,"healthDetector");c(this,"playoutDelay");c(this,"jitterBufferDelay");c(this,"_updateAudioLevelTaskId",-1);this._stats=new Zo(this,this._log),this.userManager=new $a(this.userId,this._log),this._version=ve,this.sdpSemantics=Gr,xs(e.sdpSemantics)?Yt.isUnifiedPlanDefault()&&(this.sdpSemantics=Gi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${QT()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=xs(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&hs,!xs(e.enableSPC)&&hs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Cp(this)}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.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=vu(n,[]);E.emit(T.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,d;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof b&&u.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=L();yield this.doJoin(e,(d=this.singlePC)==null?void 0:d.clientAbility),N.addSuccessEvent({key:521708,cost:L()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){N.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Ut({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var d,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ae.SETUP_FAILED,h=>{this.clearJoinTimeout(),E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),o(h)}),fe((l=(d=this.scheduleResult)==null?void 0:d.config)==null?void 0:l.singlePC)&&hs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:sd(),netType:ur(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:S.JOIN_ROOM_FAILED,message:U({key:x.JOIN_ROOM_TIMEOUT})}))},a),E.emit(T.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?X.SPC_JOIN_ROOM:X.JOIN_ROOM,n),this.signalChannel.once(F.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:_,data:I,tinyId:R}=h.data;E.emit(T.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),R&&(this.tinyId=R),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this._iceServersFromJoin=I.iceServer?[I.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var D;(D=this.singlePC)==null||D.connect(M(v({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${_}`),o(new b({code:S.JOIN_ROOM_FAILED,extraCode:m,message:U({key:x.JOIN_ROOM_FAILED,data:{error:_,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(M(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),ee.logSuccessEvent({userId:this.userId,eventType:et.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(di.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Ru&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(di.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Ko&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),ee.logFailedEvent({userId:this.userId,eventType:et.REJOIN,error:e}),this.emit("error",new b({code:S.JOIN_ROOM_FAILED,message:U({key:x.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Qm(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new Os({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new _c(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ps({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ps.EVENT_NETWORK_QUALITY,a=>{var d;this.emit("network-quality",a),(d=this.singlePC)==null||d.detectTCPAndUDP(a)})),Fe(this,this.signalChannel).add(Ae.CONNECTION_STATE_CHANGED,a=>{E.emit(T.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ae.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(F.PEER_JOIN,a=>{let{srcTinyId:d,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:d,role:u})}).add(F.PEER_LEAVE,a=>{let{userId:d,reason:l=0}=a.data.data;this.userManager.deleteUser(d,l)}).add(F.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(F.CLIENT_BANNED,a=>{let d=a.data.data,{reason:l}=d;if(ee.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}),this.signalChannel.once(Ae.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(T.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Ce(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(T.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(X.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?gm(this.userId):[],o=M(v({str_sdk_version:$s,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:ur()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(T.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(X.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",M(v({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Nc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(T.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 instanceof Ko&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?Lp:mu)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",M(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.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:F.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:d,role:l})=>({userId:a,tinyId:d,role:l}));throw U({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!au)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)===he.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof Ze&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===he.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(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()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Ko({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),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()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new mu({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(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.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 b({code:S.INVALID_OPERATION,message:U({key:x.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(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,latencyLevel:this.latencyLevel},responseCommand:F.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new b({code:S.SWITCH_ROLE_FAILED,message:U({key:x.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof b&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new b({code:S.SWITCH_ROLE_FAILED,message:U({key:x.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(d=>{d instanceof Tt&&(d instanceof si?r.audio=d:t.audio=d),d instanceof He&&(d instanceof nt&&d.mediaType===2?r.video=d:t.video=d)});let o=sn(t),n=sn(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Ru({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Ko({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",d=>{this.emit("media-connection-state-changed",M(v({},d),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",d=>{let l=d.getCode();l!==S.ICE_TRANSPORT_ERROR&&(l===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",d))}));let a=e.map(d=>d.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Tt&&(o instanceof si?r.audio=o:t.audio=o),o instanceof He&&(o instanceof nt&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");sn(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),sn(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}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||!Nd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(T.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(T.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${nc(n)}] prev: [${nc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());E.emit(T.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof b?n.getCode():S.UNKNOWN,d=n;throw n instanceof b?a===S.REMOTE_STREAM_NOT_EXIST&&(d=new b({code:S.API_CALL_ABORTED,message:U({key:x.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(d)):(d=new b({code:a,message:U({key:x.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(d)),d}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(T.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(T.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var o;Rr.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Rr.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:d}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(d.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!vd||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;Q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(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 r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(at.getTurnServer(o))):at.isPlainObject(e)&&r.push(at.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:X.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:X.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.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?F.START_PUBLISH_TENCENT_CDN_RES:F.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?F.STOP_PUBLISH_TENCENT_CDN_RES:F.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:X.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:X.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:X.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:X.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:F.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=at.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):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,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 f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:d,reSubscribeCount:l}=a;if(d.video&&t.video||d.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:d.video,smallVideo:d.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Wr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Wr}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Wr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Wr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`);let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Up(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!xs(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:S.INVALID_PARAMETER,message:U({key:x.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(!xs(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new b({code:S.INVALID_PARAMETER,message:U({key:x.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!xs(e.userDefinePushArgs))if(Up(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 b({code:S.INVALID_PARAMETER,message:U({key:x.INVALID_USER_DEFINE_PUSH_ARGS})});sn(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ni)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}};y([me(["left",B.INIT],"joined"),rt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),Jm()],Vt.prototype,"join",1),y([me("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),jm(),Aa("leave room"),Oo({fnName:"publish",validateArgs:!1}),Oo({fnName:"unsubscribe",validateArgs:!1})],Vt.prototype,"leave",1),y([ii(),Pp(),rt({settings:{retries:mi,timeout:e=>yt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(T.PUBLISH_FAILED,{room:this}))}})],Vt.prototype,"publish",1),y([Oo({fnName:"publish"}),rm("api-call"),ii(),wp(),Qe(function(){var e,t;this.localTracks.size===0&&Qi()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Vt.prototype,"unpublish",1),y([Ea(e=>{if(e.code!==S.API_CALL_ABORTED)throw e}),Oi(e=>e.userId)],Vt.prototype,"replaceTrack",1),y([Oi((...e)=>e[0].userId),ya(),qm(),rt({settings:{retries:mi,timeout:e=>yt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(T.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],Vt.prototype,"subscribe",1),y([Oo({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),Oi((...e)=>e[0].userId)],Vt.prototype,"unsubscribe",1);Qo.create=Qo._create.bind(Qo,Vt);var o$=Qo;export{o$ as default};
|