trtc.esm.js 543 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var rm=Object.create;var rs=Object.defineProperty,sm=Object.defineProperties,ol=Object.getOwnPropertyDescriptor,om=Object.getOwnPropertyDescriptors,nm=Object.getOwnPropertyNames,Do=Object.getOwnPropertySymbols,nl=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty,al=Object.prototype.propertyIsEnumerable,am=Reflect.get;var ss=Math.pow,Ea=(r,i,e)=>i in r?rs(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,N=(r,i)=>{for(var e in i||(i={}))ga.call(i,e)&&Ea(r,e,i[e]);if(Do)for(var e of Do(i))al.call(i,e)&&Ea(r,e,i[e]);return r},P=(r,i)=>sm(r,om(i));var cl=(r,i)=>{var e={};for(var t in r)ga.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&Do)for(var t of Do(r))i.indexOf(t)<0&&al.call(r,t)&&(e[t]=r[t]);return e};var Qt=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),os=(r,i)=>{for(var e in i)rs(r,e,{get:i[e],enumerable:!0})},cm=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of nm(i))!ga.call(r,s)&&s!==e&&rs(r,s,{get:()=>i[s],enumerable:!(t=ol(i,s))||t.enumerable});return r};var Ie=(r,i,e)=>(e=r!=null?rm(nl(r)):{},cm(i||!r||!r.__esModule?rs(e,"default",{value:r,enumerable:!0}):e,r));var b=(r,i,e,t)=>{for(var s=t>1?void 0:t?ol(i,e):i,o=r.length-1,n;o>=0;o--)(n=r[o])&&(s=(t?n(i,e,s):n(s))||s);return t&&s&&rs(i,e,s),s};var l=(r,i,e)=>(Ea(r,typeof i!="symbol"?i+"":i,e),e);var Ae=(r,i,e)=>am(nl(r),e,i);var f=(r,i,e)=>new Promise((t,s)=>{var o=c=>{try{a(e.next(c))}catch(d){s(d)}},n=c=>{try{a(e.throw(c))}catch(d){s(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(r,i)).next())});var Oe=Qt((R_,Ta)=>{"use strict";var dm=Object.prototype.hasOwnProperty,we="~";function ns(){}Object.create&&(ns.prototype=Object.create(null),new ns().__proto__||(we=!1));function lm(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function dl(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new lm(e,t||r,s),n=we?we+i:i;return r._events[n]?r._events[n].fn?r._events[n]=[r._events[n],o]:r._events[n].push(o):(r._events[n]=o,r._eventsCount++),r}function Oo(r,i){--r._eventsCount===0?r._events=new ns:delete r._events[i]}function De(){this._events=new ns,this._eventsCount=0}De.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)dm.call(e,t)&&i.push(we?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};De.prototype.listeners=function(i){var e=we?we+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,o=t.length,n=new Array(o);s<o;s++)n[s]=t[s].fn;return n};De.prototype.listenerCount=function(i){var e=we?we+i:i,t=this._events[e];return t?t.fn?1:t.length:0};De.prototype.emit=function(i,e,t,s,o,n){var a=we?we+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,s),!0;case 5:return c.fn.call(c.context,e,t,s,o),!0;case 6:return c.fn.call(c.context,e,t,s,o,n),!0}for(m=1,u=new Array(d-1);m<d;m++)u[m-1]=arguments[m];c.fn.apply(c.context,u)}else{var p=c.length,_;for(m=0;m<p;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),d){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,e);break;case 3:c[m].fn.call(c[m].context,e,t);break;case 4:c[m].fn.call(c[m].context,e,t,s);break;default:if(!u)for(_=1,u=new Array(d-1);_<d;_++)u[_-1]=arguments[_];c[m].fn.apply(c[m].context,u)}}return!0};De.prototype.on=function(i,e,t){return dl(this,i,e,t,!1)};De.prototype.once=function(i,e,t){return dl(this,i,e,t,!0)};De.prototype.removeListener=function(i,e,t,s){var o=we?we+i:i;if(!this._events[o])return this;if(!e)return Oo(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!s||n.once)&&(!t||n.context===t)&&Oo(this,o);else{for(var a=0,c=[],d=n.length;a<d;a++)(n[a].fn!==e||s&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:Oo(this,o)}return this};De.prototype.removeAllListeners=function(i){var e;return i?(e=we?we+i:i,this._events[e]&&Oo(this,e)):(this._events=new ns,this._eventsCount=0),this};De.prototype.off=De.prototype.removeListener;De.prototype.addListener=De.prototype.on;De.prefixed=we;De.EventEmitter=De;typeof Ta!="undefined"&&(Ta.exports=De)});var nc=Qt((JE,Ul)=>{var Vl=Ul.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Vl).forEach(function(r){var i=Vl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Fl=Qt(ai=>{var Lr=function(r){return String(Number(r))===r?Number(r):r},gp=function(r,i,e,t){if(t&&!e)i[t]=Lr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Lr(r[s+1]))},Tp=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;gp(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Bl=nc(),Sp=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ai.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(Sp).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Bl[o]||[]).length;a+=1){var c=Bl[o][a];if(c.reg.test(n))return Tp(c,t,n)}}),i.media=e,i};var $l=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Lr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};ai.parseParams=function(r){return r.split(/;\s?/).reduce($l,{})};ai.parseFmtpConfig=ai.parseParams;ai.parsePayloads=function(r){return r.toString().split(" ").map(Number)};ai.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Lr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};ai.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce($l,{})})};ai.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Lr(e):(t=Lr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Gl=Qt((qE,Hl)=>{var ac=nc(),Ip=/%[sdv%]/g,Ap=function(r){var i=1,e=arguments,t=e.length;return r.replace(Ip,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Bs=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return Ap.apply(null,s)},Cp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Rp=["i","c","b","a"];Hl.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||Cp,t=i.innerOrder||Rp,s=[];return e.forEach(function(o){ac[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(Bs(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(Bs(o,n,a))})})}),r.media.forEach(function(o){s.push(Bs("m",ac.m[0],o)),t.forEach(function(n){ac[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(Bs(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(Bs(n,a,c))})})})}),s.join(`\r
  2. `)+`\r
  3. `}});var Wl=Qt(ci=>{var ji=Fl(),yp=Gl();ci.write=yp;ci.parse=ji.parse;ci.parseParams=ji.parseParams;ci.parseFmtpConfig=ji.parseFmtpConfig;ci.parsePayloads=ji.parsePayloads;ci.parseRemoteCandidates=ji.parseRemoteCandidates;ci.parseImageAttributes=ji.parseImageAttributes;ci.parseSimulcastStreamList=ji.parseSimulcastStreamList});var $d=Qt((xO,uh)=>{var lh=uh.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(lh).forEach(function(r){var i=lh[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var ph=Qt(pi=>{var Zr=function(r){return String(Number(r))===r?Number(r):r},Qf=function(r,i,e,t){if(t&&!e)i[t]=Zr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Zr(r[s+1]))},zf=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;Qf(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},hh=$d(),Yf=RegExp.prototype.test.bind(/^([a-z])=(.*)/);pi.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(Yf).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(hh[o]||[]).length;a+=1){var c=hh[o][a];if(c.reg.test(n))return zf(c,t,n)}}),i.media=e,i};var mh=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Zr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};pi.parseParams=function(r){return r.split(/;\s?/).reduce(mh,{})};pi.parseFmtpConfig=pi.parseParams;pi.parsePayloads=function(r){return r.toString().split(" ").map(Number)};pi.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Zr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};pi.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(mh,{})})};pi.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Zr(e):(t=Zr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var _h=Qt((VO,fh)=>{var Fd=$d(),Kf=/%[sdv%]/g,Zf=function(r){var i=1,e=arguments,t=e.length;return r.replace(Kf,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},po=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return Zf.apply(null,s)},e_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],t_=["i","c","b","a"];fh.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||e_,t=i.innerOrder||t_,s=[];return e.forEach(function(o){Fd[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(po(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(po(o,n,a))})})}),r.media.forEach(function(o){s.push(po("m",Fd.m[0],o)),t.forEach(function(n){Fd[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(po(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(po(n,a,c))})})})}),s.join(`\r
  4. `)+`\r
  5. `}});var Hd=Qt(fi=>{var nr=ph(),i_=_h();fi.write=i_;fi.parse=nr.parse;fi.parseParams=nr.parseParams;fi.parseFmtpConfig=nr.parseFmtpConfig;fi.parsePayloads=nr.parsePayloads;fi.parseRemoteCandidates=nr.parseRemoteCandidates;fi.parseImageAttributes=nr.parseImageAttributes;fi.parseSimulcastStreamList=nr.parseSimulcastStreamList});import f0 from"webrtc-adapter";var ih=Ie(Oe());var ll=(O=>(O[O.INVALID_PARAMETER=4096]="INVALID_PARAMETER",O[O.INVALID_OPERATION=4097]="INVALID_OPERATION",O[O.NOT_SUPPORTED=4098]="NOT_SUPPORTED",O[O.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",O[O.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",O[O.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",O[O.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",O[O.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",O[O.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",O[O.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",O[O.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",O[O.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",O[O.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",O[O.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",O[O.CLIENT_BANNED=16448]="CLIENT_BANNED",O[O.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",O[O.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",O[O.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",O[O.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",O[O.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",O[O.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",O[O.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",O[O.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",O[O.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",O[O.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",O[O.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",O[O.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",O[O.API_CALL_ABORTED=16461]="API_CALL_ABORTED",O[O.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",O[O.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",O[O.UNKNOWN=65535]="UNKNOWN",O))(ll||{}),S=ll;var um=function(r){for(let i in S)if(S[i]===r)return i;return"UNKNOWN"},Sa=class extends Error{constructor({name:e="RtcError",message:t,code:s=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${um(s)} 0x${s.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);l(this,"code");l(this,"extraCode");l(this,"message");l(this,"originMessage");l(this,"name");l(this,"constraint");this.code=s,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},R=Sa;var ul=new Date().getTime(),Ia=0,hl=function(r){ul=r,Ia=ul-new Date().getTime();let i=new Date;i.setTime(r),A.info(`baseTime from server: ${i} offset: ${Ia}`)},as=function(){return new Date().getTime()+Ia},Mo=function(){let r=new Date;return r.setTime(as()),r.toLocaleString()};var Ve={};os(Ve,{bytes2ms:()=>rp,convertObjectNumberToInt:()=>cn,copyProperties:()=>ip,deepClone:()=>Dr,deepMerge:()=>ni,delay:()=>Mr,fibonacci:()=>vr,formatedTime:()=>hp,getAbilityConfigUrl:()=>Dl,getConstructorName:()=>nn,getContainerFromElement:()=>lp,getEnv:()=>tp,getInternalVersion:()=>ap,getLoggerUrl:()=>yi,getMuteStateFromFlag:()=>Ni,getNetworkType:()=>kl,getNumNetworkType:()=>Or,getReconnectionTimeout:()=>Lt,getStringByteLength:()=>an,getTurnServer:()=>dp,getUint32Version:()=>ic,getValueType:()=>ge,getViewListFromView:()=>ws,glog:()=>wl,ipv4ToUint32:()=>xs,isArray:()=>fe,isAudioWorkletSupported:()=>np,isBoolean:()=>le,isConstructor:()=>Ps,isEmpty:()=>Za,isFunction:()=>te,isLangChinese:()=>vt,isMediaStreamTrack:()=>op,isNumber:()=>ee,isObject:()=>_t,isOverseaSdkAppId:()=>Os,isPlainObject:()=>Je,isPortrait:()=>tc,isPromise:()=>Ls,isRemoteTrack:()=>gt,isString:()=>z,isUndefined:()=>g,loadImage:()=>Vs,ms2bytes:()=>sp,ms2samples:()=>xl,performanceNow:()=>w,promiseAny:()=>Ms,samples2ms:()=>Pl,setNetworkType:()=>Ka,stringify:()=>Et,stringifyIncludeValue:()=>ec,throttlePromise:()=>rc});var Pa={};os(Pa,{AUDIO_MUTE_BIT:()=>Vo,AUDIO_STAT_BIT:()=>Ti,AUX_STAT_BIT:()=>$i,AUX_STREAM_MSID:()=>ba,BACKEND_ENV:()=>wo,BASE_DOC_URL:()=>yt,BASE_HOST:()=>ml,CAPABILITIES_KEYS:()=>$o,CLASS_NAME:()=>km,CLOUD_CONSOLE_URL:()=>fm,DATA_FREEZE_TIMING:()=>Bo,DOC_URL:()=>_m,DTLS_STATE_UNKNOWN:()=>at,ENV_NAME:()=>zt,EXCHANGE_SDP_TIMEOUT:()=>Ma,INTERVAL:()=>Gi,IS_WORKER:()=>ur,IS_WORKLET:()=>ds,KIBANA_EVENT:()=>Ue,LOCAL_STREAM_PUBLISH_STATE:()=>_l,LOGGER_CMD_TYPE:()=>Ei,LOGGER_DOMAIN:()=>Ca,LOGGER_DOMAIN_OVERSEA:()=>Ra,LOG_LEVEL:()=>nt,LOG_LEVEL_NAME:()=>Pm,MAIN_STREAM_MSID:()=>hs,MAX_RTT:()=>fs,MICROPHONE_COMMUNICATIONS:()=>Lm,MICROPHONE_DEFAULT:()=>Hi,NAME:()=>h,NETWORK_TYPE:()=>ko,NOT_SUPPORTED_H264:()=>Fi,PAUSED_RETRY_COUNT:()=>ka,PEERCONNECTION_CONNECTING_TIMEOUT:()=>ms,PEER_CONNECTION_STATE:()=>oe,PEER_LEAVE_REASON:()=>La,RAF:()=>fr,RECOVER_CAPTURE_INTERVAL:()=>pr,REMOTE_STREAM_TYPE_AUX:()=>va,REMOTE_STREAM_TYPE_MAIN:()=>Na,RENDER_FREEZE_TIMING:()=>vm,RIC:()=>Ii,SCHEDULE_DOMAIN:()=>ct,SCHEDULE_TIMEOUT:()=>Mm,SDP_SEMANTICS_PLAN_B:()=>hr,SDP_SEMANTICS_UNIFIED_PLAN:()=>Si,SECOND_HOST:()=>mm,SIGNAL_PING_PONG_INTERVAL:()=>gm,SIGNAL_PING_TIMEOUT:()=>Em,SIGNAL_RECONNECTION_COUNT:()=>bm,SMALL_STAT_BIT:()=>us,SPEAKER_DEFAULT:()=>ps,STORAGE_EXPIRES_TIME:()=>Lo,STREAM_TYPE_BIG:()=>Dm,STREAM_TYPE_SMALL:()=>Om,SUBSCRIBE_SMALL_RETRY_COUNT:()=>mr,SYNC_USER_LIST_INTERVAL:()=>Nm,Scene:()=>bt,Switch:()=>pl,THIRD_HOST:()=>pm,TIMEOUT:()=>Ai,TRANSPORT_DIRECTION:()=>Q,TRTC_ERROR_ASSISTANCE:()=>ya,TRTC_QUALITY_BAD:()=>Cm,TRTC_QUALITY_DISCONNECTED:()=>ym,TRTC_QUALITY_EXCELLENT:()=>Sm,TRTC_QUALITY_GOOD:()=>Im,TRTC_QUALITY_POOR:()=>Am,TRTC_QUALITY_UNKNOWN:()=>Tm,TRTC_QUALITY_VERY_BAD:()=>Rm,UPDATE_OFFER_TIMEOUT:()=>Oa,VIDEO_MUTE_BIT:()=>Uo,VIDEO_STAT_BIT:()=>gi,audioProfileMap:()=>Po,getRetryCount:()=>Yt,getScriptDir:()=>hm,innerVersion:()=>cs,loggerProxy:()=>ls,screenProfileMap:()=>xo,setLoggerProxy:()=>Bi,setRetryCount:()=>Da,setVersion:()=>Aa,version:()=>ye,videoProfileMap:()=>Ze});var cs="4.15.00.1600",ye="5.0.0";function Aa(r){ye=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));cs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var ur=typeof importScripts!="undefined",ds=typeof registerProcessor!="undefined",hm=()=>{let r=ur?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},ls="",Bi=r=>ls=r,ml="web.sdk.qcloud.com",mm="web.sdk.tencent.cn",pm="web.sdk.cloud.tencent.cn",fm="https://console.cloud.tencent.com/trtc",yt=`https://${ml}/trtc/webrtc/v5/doc`,_m=`${yt}/zh-cn/`,Ca="https://yun.tim.qq.com",Ra="https://apisgp.my-imcloud.com",ya="trtc_error_assistance",Ei={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},zt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},nt=(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))(nt||{}),Em=18e3,gm=2e3,ko={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Lo=7*24*3600*1e3,pl=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(pl||{}),Po={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}},Ze={"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}},xo={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},h={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Q={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},wo={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},bt=(e=>(e.LIVE="live",e.RTC="rtc",e))(bt||{}),gi=1,us=2,$i=4,Ti=8,Vo=64,Uo=16,hs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ba="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Na=h.MAIN,va=h.AUXILIARY,Tm=0,Sm=1,Im=2,Am=3,Cm=4,Rm=5,ym=6,at="unknown",oe={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},fl=1/0;function Da(r){fl=r}function Yt(){return fl}var bm=30,Ue={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"},Nm=1e4,Oa=1e4,Ma=1e4,Si="unified-plan",hr="plan-b",Fi=1028,_l=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(_l||{}),Bo=500,vm=1e3,Dm=h.BIG,Om=h.SMALL,ms=10*1e3,ct={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},Mm=2e3,km={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ka=5,Hi="default",ps=Hi,Lm="communications",Pm=Object.keys(nt),La=["normal leave","timeout leave","kick","role change"],mr=10,pr=2e3,Ii="ric",fr="raf",Gi="interval",Ai="timeout",$o=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],fs=10*1e3;function Kt({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((o,n)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);o({data:a})}catch(a){o({data:s.response})}else n({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function xa(r){return f(this,null,function*(){let i=w(),e=JSON.stringify(r);try{if(!CompressionStream||e.length<=2800)return e;let s=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(s)).blob()).arrayBuffer();return A.debug(`compressJSON ${e.length} -> ${a.byteLength} ${w()-i}ms`),a}catch(t){return e}})}var dt=1e8;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"},Ce={AVOID_REPEATED_CALL(r){return`previous ${r.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${ge(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${ge(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:r,rule:i,fnName:e,value:t}){return`the min value of ${r||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:r,rule:i,fnName:e,value:t}){return`the max value of ${r||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(r){return`${r.commandDesc||r.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(r){return`SignalChannel setup failure: (errorCode: ${r.errorCode}, errorMsg: ${r.errorMsg} }).`},ERROR_MESSAGE(r){let i=`${r.type} failed`;return r.message&&(i=`${i}: ${r.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(r){return`exchange sdp failed ${r.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(r){return`'${r}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(r){return`'${r}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:r,code:i}){return`Failed to join room - ${r} code: ${i}`},REJOIN_ROOM_FAILED(r){return`reJoin room: ${r.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:`no permission to publish() under live/${"audience"}, please call switchRole("${"anchor"}") firstly before publish().`,INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(r){return`duplicate ${r} stream publishing, please unpublish your prev ${r} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:r,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${r}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:`role could only be set to a value as ${"anchor"} or ${"audience"}.`,INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(r){return`switchRole failed, errCode: ${r.code} errMsg: ${r.message}.`},CLIENT_BANNED(r){return`client was banned because of ${r.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(r){return`startPublishCDNStream failed, errMsg: ${r.message}.`},STOP_PUBLISH_CDN_FAILED(r){return`stopPublishCDNStream failed, errMsg: ${r.message}.`},INVALID_STREAM_ID(r){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(r){return`cannot replace ${r.kind} track because stream has not ${r.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(r){return`startMixTranscode failed, errMsg: ${r.message}.`},STOP_MIX_TRANSCODE_FAILED(r){return`stopMixTranscode failed, errMsg: ${r.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(r){return`'${r}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:r,fnName:i})=>`'${r}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:r,fnName:i,type:e})=>`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:r=>`${r.media} play failed\uFF0Cbrowser exception: ${r.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(r){return`${r}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(r){return`${r.signalResponse} failed, response code is ${r.code} , errMsg: ${r.message}.`},CATCH_HANDLER_ERROR({name:r,event:i}){return`an error was caught in ${r}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:r}){return`experimental api ${r} does not exist.`},REPEAT_JOIN:r=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:r}){return`failed to call ${r}() because client was destroyed.`},SEI_NOT_SUPPORT:r=>`not support to sendSEIMessage${r===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:r,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${r?"size":"times"} is over ${r?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(r){return`connection aborted due to: ${r}`},API_CALL_ABORTED(r){let i;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${r.userId} ${r.streamType} stream aborted, reason: remote user ${r.userId} unpublished stream.`:i=`API aborted, reason: ${r.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:r=>`'streamType' is required when 'userId' is not '*', calling ${r}()`};var br={};os(br,{ANDROID_VERSION:()=>Ua,CHROME_MAJOR_VERSION:()=>ft,CHROME_VERSION:()=>sn,EDGE_VERSION:()=>Ho,EDG_MAJOR_VERSION:()=>$a,EDG_VERSION:()=>Go,FIREFOX_MAJOR_VERSION:()=>Ba,FIREFOX_VERSION:()=>Fo,HUAWEI_VERSION:()=>Zo,IE_VERSION:()=>Bm,IOS_MAIN_VERSION:()=>Ns,IOS_VERSION:()=>Ri,IPADQQB_VERSION:()=>Yo,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>Wa,IS_ANY_SAFARI:()=>yr,IS_CHROME:()=>Rr,IS_CHROME_OS:()=>Fa,IS_CHROMIUM_BASE:()=>pt,IS_EDG:()=>gr,IS_EDGE:()=>Er,IS_ELECTRON:()=>Fm,IS_FIREFOX:()=>re,IS_HEADLESS_CHROME:()=>Ga,IS_HUAWEI:()=>Hm,IS_HUAWEIBROWSER:()=>ys,IS_IE:()=>Sl,IS_IE8:()=>Um,IS_IOS:()=>Be,IS_IOS_13_OR_14:()=>ja,IS_IOS_15_1:()=>Ja,IS_IPAD:()=>_s,IS_IPADQQB:()=>As,IS_IPAD_PRO:()=>Va,IS_IPHONE:()=>Wi,IS_IPOD:()=>Tl,IS_LINUX:()=>Cs,IS_LOCAL:()=>ti,IS_MAC:()=>mt,IS_MACQQB:()=>Is,IS_MIBROWSER:()=>Rs,IS_MQQB:()=>Ir,IS_NATIVE_ANDROID:()=>Vm,IS_OLD_ANDROID:()=>wm,IS_OPPOBROWSER:()=>Ar,IS_SAFARI:()=>$e,IS_SAFARI_15_1:()=>Gm,IS_SAMSUNGBROWSER:()=>bs,IS_SOGOU:()=>gs,IS_SOGOUM:()=>Es,IS_TBS:()=>ht,IS_UCBROWSER:()=>Ha,IS_VIVOBROWSER:()=>Cr,IS_WECHAT:()=>Tr,IS_WIN:()=>Zt,IS_WQQB:()=>Ss,IS_WX:()=>$m,IS_X5MQQB:()=>Sr,IS_XWEB:()=>Ts,MACQQB_VERSION:()=>zo,MI_VERSION:()=>Ko,MQQB_VERSION:()=>_r,OPPO_VERSION:()=>tn,SAFARI_VERSION:()=>Ci,SAMSUNG_VERSION:()=>en,SOGOUM_VERSION:()=>Wo,SOGOU_VERSION:()=>Jo,TBS_VERSION:()=>jo,UA_DATA_STRING:()=>lt,USER_AGENT:()=>ut,VIVO_VERSION:()=>rn,WECHAT_VERSION:()=>Xo,WQQB_VERSION:()=>Qo,XWEB_VERSION:()=>qo,browserInfo:()=>Nt,getBrowserInfo:()=>Il,getChromeMajorVersion:()=>ei,getDeviceModel:()=>Ji,getOSName:()=>on,getOSNumber:()=>Ds,getOSString:()=>ri,getOSType:()=>Wm,getTerminalType:()=>qa,getUserAgentData:()=>vs,isLocalStorageEnabled:()=>ii});var ut=typeof navigator=="undefined"?"":navigator.userAgent,q=r=>new RegExp(r,"i").test(ut),Te=r=>{if(q(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=ut.match(i);if(e&&e[1])return e[1]}return""},wa=r=>{if(q(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=ut.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},El=/AppleWebKit\/([\d.]+)/i.exec(ut),xm=El?parseFloat(El[1]):NaN,_s=q("iPad"),Va=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&q("Macintosh"),Wi=q("iPhone")&&!_s,Tl=q("iPod"),Be=Wi||_s||Tl||Va,pe=q("Android"),Ua=function(){if(pe){let r=ut.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(r){let i=r[1]&&parseFloat(r[1]),e=r[2]&&parseFloat(r[2]);if(i&&e)return parseFloat(`${r[1]}.${r[2]}`);if(i)return i}}return NaN}(),wm=pe&&q("webkit")&&Ua<2.3,Vm=pe&&Ua<5&&xm<537,re=q("Firefox"),Fo=Te("Firefox"),Ba=wa("Firefox"),Er=q("Edge"),Ho=Te("Edge"),gr=q("Edg"),Go=Te("Edg"),$a=wa("Edg"),Es=q("SogouMobileBrowser"),Wo=Te("SogouMobileBrowser"),gs=q("MetaSr\\s"),Jo=Te("MetaSr\\s"),ht=q("TBS"),jo=Te("TBS"),Ts=q("XWEB"),qo=Te("XWEB"),Um=q("MSIE\\s8\\.0"),Sl=q("MSIE\\/\\d+"),Bm=function(){if(Sl){let r=/MSIE\s(\d+)\.\d/.exec(ut),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(ut)&&/rv:11.0/.test(ut)&&(i=11),i}return NaN}(),Tr=q("(micromessenger|webbrowser)"),Xo=Te("MicroMessenger"),Sr=!ht&&q("MQQBrowser")&&q("COVC"),Ir=!ht&&q("MQQBrowser")&&!q("COVC"),_r=Ir||Sr?Te("MQQBrowser"):"",Ss=!ht&&q(" QQBrowser"),Qo=Te(" QQBrowser"),Is=!ht&&q("QQBrowserLite"),zo=Te("QQBrowserLite"),As=!ht&&q("MQBHD"),Yo=Te("MQBHD"),Zt=q("Windows"),mt=!Be&&q("MAC OS X"),Cs=!pe&&q("Linux"),Fa=q("CrOS"),$m=q("MicroMessenger"),Ha=q("UCBrowser"),Fm=q("Electron"),Rs=q("MiuiBrowser"),Ko=Te("MiuiBrowser"),ys=q("HuaweiBrowser"),Hm=q("Huawei"),Zo=Te("HuaweiBrowser"),bs=q("SamsungBrowser"),en=Te("SamsungBrowser"),Ar=q("HeyTapBrowser"),tn=Te("HeyTapBrowser"),Cr=q("VivoBrowser"),rn=Te("VivoBrowser"),ei=()=>wa("Chrome"),pt=q("Chrome"),Rr=!Er&&!gs&&!Es&&!ht&&!Ts&&!gr&&!Ss&&!Rs&&!ys&&!bs&&!Ar&&!Cr&&pt,Ga=q("HeadlessChrome"),ft=ei(),sn=Te("Chrome"),$e=!pt&&!Ir&&!Sr&&!Is&&!As&&q("Safari"),yr=$e||Be,Ci=Te("Version"),Wa=/Android.*(wv|.0.0.0)/.test(ut),Ri=(()=>{if(Va)return Ci;if(Be){let r=ut.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),Ns=Number(Ri.split(".")[0]),Gm=Ci==="15.1",Ja=Ri==="15.1",ja=(()=>{let r=Number(Ri.split(".")[0]);return r===14||r===13})(),ti=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",ii=(()=>{let r;return()=>{if(typeof r=="undefined")try{r=!!window.localStorage}catch(i){r=!1}return r}})(),Nt=Il();function Il(){let r=new Map([[re,["Firefox",Fo]],[gr,["Edg",Go]],[Rr,["Chrome",sn]],[$e,["Safari",Ci]],[ht,["TBS",jo]],[Ts,["XWEB",qo]],[Tr&&Wi,["WeChat",Xo]],[Ss,["QQ(Win)",Qo]],[Ir,["QQ(Mobile)",_r]],[Sr,["QQ(Mobile X5)",_r]],[Is,["QQ(Mac)",zo]],[As,["QQ(iPad)",Yo]],[Rs,["MI",Ko]],[ys,["HW",Zo]],[bs,["Samsung",en]],[Ar,["OPPO",tn]],[Cr,["VIVO",rn]],[Er,["EDGE",Ho]],[Es,["SogouMobile",Wo]],[gs,["Sogou",Jo]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var ie=null,lt="";function vs(){return f(this,null,function*(){if(ie)return ie;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return ie=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ie&&!lt&&(lt=`UAData: ${ie.platform}/${ie.platformVersion}`,ie.architecture&&ie.bitness&&(lt+=` ${ie.architecture}/${ie.bitness}`),ie.mobile&&(lt+=" mobile"),ie.model&&(lt+=` model: ${ie.model}`),ie.fullVersionList&&(lt+=` ${ie.fullVersionList.filter(r=>r.brand!=="Not/A)Brand").map(r=>`${r.brand}/${r.version}`).join(",")}`)),ie}catch(r){return null}})}function Ji(){return(ie==null?void 0:ie.model)||""}var gl=new Map([[pe,"Android"],[Be,"iOS"],[Zt,"Windows"],[mt,"MacOS"],[Cs,"Linux"],[Fa,"ChromeOS"]]),on=function(){return gl.get(!0)?gl.get(!0):ie?ie.platform:"unknown"};function Ds(){return Zt?1:pe?2:mt?3:Be?4:Cs?5:Fa?6:0}var ri=()=>{let r=on();return r+=`/${Nt.name}/${$e?Nt.version:Nt.version.split(".")[0]}`,ie!=null&&ie.platformVersion&&(r+=`/${ie.platformVersion}`),ie!=null&&ie.architecture&&(r+=`/${ie.architecture}`),r};function qa(){return pe?4:Wi?2:_s?3:mt?12:Zt?5:Cs?13:1}function Wm(){return pe?"Android":Wi?"iPhone":_s?"iPad":mt?"Mac":Zt?"Windows":Cs?"Linux":"unknown"}var Al=(r,i)=>i?`${yt}/${r}/${i}`:`${yt}/${r}/index.html`;var Jm=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let r=localStorage==null?void 0:localStorage.getItem(ya);if(r){r=JSON.parse(r);let i=document.createElement("script");i.type="text/javascript",i.text=r.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function x(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,o="",n="",a="";te(Ce[i])?o=Ce[i](e):z(Ce[i])&&(o=Ce[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Jm();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(te(d[i])?a=d[i](e):z(d[i])&&(a=d[i]));let u=o;return vt()&&(c&&c[i]&&(te(c[i])?n=c[i](e):z(c[i])&&(n=c[i])),n&&(s?u=`${n}
  6. \u8BF7\u67E5\u770B\u6587\u6863: ${Al("zh-cn",a)}
  7. `:u=`${n}
  8. `,u+=o)),s&&(u+=`
  9. Refer to: ${Al("en",a)}
  10. `),u}var jm=Object.prototype.hasOwnProperty;var Dt=r=>typeof r=="function",si=r=>typeof r=="undefined";var Cl=r=>typeof r=="boolean";var qm=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Rl(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(qm(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(jm.call(r,i))return!1;return!0}}return!1}var Xm=0,Qm=1,yl=2;function zm({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,u=0,m=-1,p=Xm,_=(C,y)=>f(this,null,function*(){let D=n||this;try{let B=yield r.apply(D,a);u>0&&o&&o.call(this,u),u=0,C(B)}catch(B){let ve=()=>{clearTimeout(m),u=0,p=yl,y(B)},vo=()=>{p!==yl&&u<(Dt(c)?c():c)?(u++,p=Qm,Dt(t)&&t.call(this,u,ve),m=window.setTimeout(()=>{m=-1,_(C,y)},Dt(d)?d(u):d)):(ve(),Dt(s)&&s.call(this,B))};Dt(e)?e.call(this,{error:B,retry:vo,reject:y,retryFuncArgs:a,retriedCount:u}):vo()}});return new Promise(_)}}var Ot=zm;var bl=Ie(Oe(),1),Ym=new bl.default,T=Ym;var oi=($=>($.ROOM_DESTROY="1",$.JOIN_START="21",$.JOIN_SCHEDULE_SUCCESS="22",$.JOIN_SIGNAL_CONNECTION_START="23",$.JOIN_SIGNAL_CONNECTION_END="24",$.JOIN_SEND_CMD="25",$.JOIN_RECEIVED_CMD_RES="26",$.JOIN_SUCCESS="27",$.JOIN_FAILED="28",$.LEAVE_START="51",$.LEAVE_SEND_CMD="52",$.LEAVE_SUCCESS="53",$.PUBLISH_START="61",$.SEND_FIRST_VIDEO_FRAME="62",$.PUBLISH_FAILED="63",$.SUBSCRIBE_START="81",$.SUBSCRIBE_SUCCESS="82",$.SUBSCRIBE_FAILED="84",$.UNSUBSCRIBE_SUCCESS="83",$.LOCAL_TRACK_CAPTURE_START="101",$.LOCAL_TRACK_CAPTURE_SUCCESS="102",$.LOCAL_TRACK_CAPTURE_FAILED="103",$.LOCAL_TRACK_PUBLISHED="104",$.LOCAL_TRACK_UNPUBLISHED="105",$.LOCAL_TRACK_REPLACED="106",$.SWITCH_DEVICE_SUCCESS="107",$.TRACK_MUTED="108",$.TRACK_UNMUTED="109",$.REMOTE_TRACK_SUBSCRIBED="110",$.REMOTE_TRACK_UNSUBSCRIBED="111",$.LOCAL_TRACK_RECAPTURE="112",$.PLAY_TRACK_START="151",$.PLAYER_STATE_CHANGED="152",$.VIDEO_LOADED_DATA="153",$.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",$.SIGNAL_CONNECTION_STATE_CHANGED="201",$.PEER_CONNECTION_STATE_CHANGED="202",$.SINGLE_CONNECTION_STAT="203",$.SPC_RECONNECTED="204",$.HEARTBEAT_REPORT="251",$.RECEIVED_PUBLISHED_USER_LIST="252",$.REMOTE_PUBLISH_STATE_CHANGED="253",$.AUDIO_LEVEL_INTERVAL="260",$.NETWORK_QUALITY="261",$.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",$.QUALITY_LIMITATION_CHANGED="263",$.LOG="264",$))(oi||{});var Xa=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:ye,env:zt.QCLOUD,browserVersion:Nt.name+Nt.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:s}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(s))}logSuccessEvent(i){ti||!A.isAbleToUpload||this._configs.env===zt.QCLOUD&&this.uploadEventToKibana(P(N({},i),{result:"success"}))}logFailedEvent(i){if(ti||!A.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||S.UNKNOWN};this._configs.env===zt.QCLOUD&&this.uploadEventToKibana(P(N({},n),{error:s}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let s={timestamp:Mo(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:ye,log:i};t&&(s.errorInfo=t.message,t.stack&&(s.errorInfo+=`
  11. ${t.stack}`)),this.sendRequest(yi(this._configs.sdkAppId,Ei.LOG),s)}sendRequest(i,e){if(!A.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}Kt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},Y=new Xa;var Qa=null,za=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(ct).map(r=>`<link rel="dns-prefetch" href="https://${r}">`).join(`\r
  12. `));function kt(r){le(r)&&r!==za&&(za=r,A.info(`setIsNeedToSchedule ${r}`))}T.on("28",()=>kt(!0));T.on("63",()=>kt(!0));T.on("84",()=>kt(!0));T.on("201",r=>{r.state==="RECONNECTING"&&kt(!0)});T.on("202",r=>{r.state==="RECONNECTING"&&kt(!0)});function Km(r,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let s=performance.getEntriesByType("resource"),o=Nr(r,h.MAIN),n=Nr(r,h.BACKUP);for(let a of s)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?h.MAIN:h.BACKUP,d=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),C=Math.round(a.requestStart-a.secureConnectionStart),y=Math.round(a.secureConnectionStart-a.connectStart),D=Math.round(a.responseStart-a.requestStart),B=Math.round(a.responseEnd-a.responseStart),ve=[_,C,y,D,B];Y.uploadEvent({log:`stat-schedule-net:${d}(${u}(${m}->${p})->${ve.join("->")}) ${c}`,userId:i}),t=P(N({},t),{totalCost:d,local:u,dns:_,tcp:y,tls:C,request:D,response:B});break}}catch(s){A.error("getScheduleDetailCost error",s)}return t}function vl(d){return f(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!za&&Qa)return{isCached:!0,result:Qa};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(r)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",o),m.append("userSig",String(s)),a&&m.append("role",String(a)),c&&m.append("latencyLevel",String(c)),n&&m.append("frameWorkType",String(n));let p=w(),_=yield ep(m,u,i);_.config&&(_.config.loggerDomain&&Bi(_.config.loggerDomain),le(_.config.scheduleCache)&&kt(!_.config.scheduleCache)),u.delta=w()-p;let C=Km(Number(i),r,p);return Qa=_,{isCached:!1,result:_,detailCost:C}}catch(m){let p=fe(m)?m[0]:m,_=ee(p.code)?p.code:0,C=`schedule failed${p.message?`: ${p.message}`:""}`,y=new R({code:S.SCHEDULE_FAILED,extraCode:_,message:x({key:L.JOIN_ROOM_FAILED,data:{error:C,code:_}})});throw A.error(C,_),y}})}var bi={main:"",backup:""};function Ya(r){fe(r)?(bi.main=r[0],bi.backup=r[1]):bi.main=r}function Nr(r,i=h.MAIN,e=!1){return`https://${bi[i]||Ol(r,i,e)}/api/v1/config`}function Dl(r,i=h.MAIN){return`https://${bi[i]||Ol(r,i)}/api/v1/trtcAutoConf`}function Ol(r,i=h.MAIN,e=!1){if(Os(r))return i===h.MAIN?ct.MAIN_OVERSEA:ct.BACKUP_OVERSEA;let t;return Os(r)?e?t=i===h.MAIN?ct.MAIN_OVERSEA_OLD:ct.BACKUP_OVERSEA_OLD:t=i===h.MAIN?ct.MAIN_OVERSEA:ct.BACKUP_OVERSEA:t=i===h.MAIN?ct.MAIN:ct.BACKUP,t}function Zm(r,i,e){return new Promise((t,s)=>{Kt({url:r,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var Nl=(r,i)=>Ot({retryFunction:Zm,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function ep(r,i,e){return new Promise((t,s)=>{let o=null;Ms([Nl(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=n.message,o||(c>=2&&(d[0]=Nr(e,h.MAIN,!0)),a())})(Nr(e,h.MAIN),r,{get timeout(){return vr(2+i.count[0])*1e3}}),Nl(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=n.message,o||(c>=2&&(d[0]=Nr(e,h.BACKUP,!0)),a())})(Nr(e,h.BACKUP),r,{get timeout(){return vr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var tp=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Os=r=>Number(r)<14e8,yi=function(r,i){let e;ls?e=ls:e=Os(r)?Ra:Ca;let t=Math.floor(Math.random()*ss(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},ks="unknown";function kl(){if(ks!=="unknown")return ks;let{userAgent:r,connection:i}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),s=i&&i.effectiveType&&i.effectiveType.toLowerCase();return s==="slow-2"&&(s="2g"),t&&(ks=Ll(t,s)),ks}function Ll(r,i){if(ko[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ka(r){ks=Ll(r)}function Or(){return ko[kl()]}function ip(r,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(r,e,t)}return r}function rp(r,i=48e3){return Pl(r/4,i)}function Pl(r,i=48e3){return r*1e3/i}function sp(r,i=48e3){return xl(r,i)*4}function xl(r,i=48e3){return r*i/1e3}var wl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},vt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Je=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function vr(r,i=1,e=1){return r<=1?e:vr(r-1,e,i+e)}function Lt(r){return r>8?30*1e3:vr(r)*1e3}function ge(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var te=r=>typeof r=="function",g=r=>typeof r=="undefined",z=r=>typeof r=="string",ee=r=>typeof r=="number",le=r=>typeof r=="boolean",_t=r=>ge(r)==="object",fe=r=>ge(r)==="array",op=r=>ge(r)==="MediaStreamTrack".toLowerCase(),gt=r=>r.isRemote,Ls=r=>ge(r)==="promise",Ps=r=>te(r)&&r.prototype.constructor===r,nn=r=>Ps(r)?r.prototype.constructor.name:"",np=typeof AudioWorkletNode!="undefined";function Ms(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(o=>{t.push(o),t.length===r.length&&e(t)})})})}function w(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Ml=r=>+r<10?`0${r}`:r,ap=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=Ml(e[1])+Ml(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},cp=Object.prototype.hasOwnProperty,{toString:AE}=Object.prototype;function Za(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(cp.call(r,i))return!1;return!0}}return!1}function Ni(r,i){return{userId:i,hasAudio:!!(r&Ti),hasVideo:!!(r&gi),hasAuxiliary:!!(r&$i),hasSmall:!!(r&us),audioMuted:!!(r&Vo),videoMuted:!!(r&Uo),audioAvailable:!!(r&Ti)&&!(r&Vo),videoAvailable:!!(r&gi)&&!(r&Uo)}}function dp(r){let i={urls:r.url.startsWith("turn:")||r.url.startsWith("turns:")?r.url:`turn:${r.url}`};return!g(r.username)&&!g(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",g(r.credentialType)||(i.credentialType=r.credentialType)),i}function xs(r,i=!0){if(!z(r))return 0;let e=r.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ni=function(r,i,e,t){if(!(_t(r)&&_t(i)))return 0;let s=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(g(i[n])||e&&e.includes(n)))if(_t(r[n])&&_t(i[n]))s+=ni(r[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;r[n]!==i[n]&&(r[n]=Dr(i[n]),s+=1)}return s};function Dr(r){if(fe(r)){let i=[];return r.forEach((e,t)=>{i[t]=Dr(e)}),i}if(_t(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=Dr(r[e])}),i}return r}var ws=r=>{let i=[];if(fe(r))i=[...r];else if(z(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},lp=r=>z(r)?document.getElementById(r):r,up=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),hp=()=>up.format(new Date);function Et(r,{keysToInclude:i,keysToExclude:e}){try{if(fe(r))return`[${r.map(n=>Et(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Je(r)||!fe(i)&&!fe(e))return JSON.stringify(r);let t={},s=new Set(i),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(t[n]=Je(r[n])||fe(r[n])?JSON.parse(Et(r[n],{keysToExclude:e,keysToInclude:i})):r[n])}),JSON.stringify(t)}catch(t){return"{}"}}function ec(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),Et(r,{keysToInclude:e})}function an(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var tc=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Vs=r=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(z(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new R({code:S.INVALID_PARAMETER,message:`load image failed, url: ${r}`}))}})}),ic=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},cn=r=>(Object.keys(r).forEach(i=>{ee(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Je(r[i])||fe(r[i]))&&cn(r[i])}),r);function Mr(r){return new Promise(i=>setTimeout(i,r))}var rc=(r,i)=>{let e=null;return function(...t){return e||(e=r.apply(i||this,t),e.finally(()=>e=null),e)}};var kr=class{constructor(i){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Cl(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),A.log(i,e,si(this.userId)||Rl(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 E=oi;var mp="%cTRTC%c%s",pp="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",fp="display: inline",_p=!(Be||pe||Ga),sc=class{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!ur&&!ds&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&nt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(E.JOIN_FAILED,()=>{this.startUpload()}),T.on(E.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:o})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})});else if(z(t.userId)&&ee(t.sdkAppId)){let{userId:s,sdkAppId:o}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return 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 s=[...i.values()];for(let o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:c}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Mo(),sdkAppId:String(a),userId:n,version:ye,log:c.map(d=>d.log).join(`
  13. `)}),a),c.forEach(d=>d.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Ot({retryFunction:()=>Kt({url:yi(e,Ei.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(as());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${nt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){g(nt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(z(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((d,u)=>`${d} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:s,sdkAppId:o,forAllJoinedClients:t};if(T.emit(E.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=nt[i])==null?void 0:c.toLowerCase())||"info";_p?console[a](mp,pp,fp,...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 kr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;nt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},A=new sc;var Ep=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let i=Math.random()*16|0;return(r=="x"?i:i&3|8).toString(16)})},Us=Ep;var oc=class{constructor(){l(this,"_prefix","TRTC");l(this,"_queue",new Map);this.checkStorage()}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)){let s=localStorage.getItem(t);if(!s)return!1;let o=JSON.parse(s);if(o&&o.expiresIn<Date.now())return!0}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){A.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){A.warn(e)}}setItem(i,e){if(!!ii())try{let t={expiresIn:Date.now()+Lo,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){A.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 A.warn(e),!1}}clear(){if(!!ii())try{localStorage.clear()}catch(i){A.warn(i)}}},dn=new oc;var wt={};os(wt,{HTTPS_API:()=>Pp,IS_GET_CAPABILITIES_SUPPORTED:()=>_c,IS_GET_SETTINGS_SUPPORTED:()=>xt,IS_INSERTABLE_STREAM_SUPPORTED:()=>Tt,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>En,IS_SEI_SUPPORTED:()=>Gs,IS_SPC_SUPPORTED:()=>Pr,basis:()=>Up,checkSystemRequirementsInternal:()=>_n,decodeSupportStatus:()=>fn,encodeSupportStatus:()=>mc,getBrowserInfo:()=>Op,getDisplayResolution:()=>ql,isAddTransceiverSupported:()=>tt,isBrowserSupported:()=>pc,isGetReceiversSupported:()=>Xi,isGetSendersSupported:()=>Di,isGetTransceiversSupported:()=>Pt,isGetUserMediaSupported:()=>Xl,isMediaDevicesSupported:()=>pn,isMediaSessionSupported:()=>Yl,isMediaStreamTrackProcessorSupported:()=>Mp,isReplaceTrackSupported:()=>fc,isRequestVideoFrameCallbackSupported:()=>Qi,isSIMDSupported:()=>Vp,isScreenCaptureApiAvailable:()=>$s,isSelectedCandidatePair:()=>vi,isSetParametersSupported:()=>Hs,isSmallStreamAPISupported:()=>zl,isSmallStreamSupported:()=>Fs,isStopTransceiverSupported:()=>wp,isTRTCSupported:()=>kp,isUnifiedPlanDefault:()=>xp,isUsedInHttpProtocol:()=>di,isWebAudioSupported:()=>Ql,isWebCodecSupported:()=>gn,isWebCodecsSupported:()=>jl,isWebRTCSupported:()=>Ec,isWebTransportSupported:()=>Kl});var hc=Ie(Wl(),1);var bp=1,Np=0,ln=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=A.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?un.START_MICROPHONE:cc.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?un.START_MICROPHONE:cc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:ic(this.version||ye),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,o])=>({uint32_item_key:s,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 s=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(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:s}){if(!!i&&(this.addEnum({key:i,value:bp,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(ee(e)?t=e:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Np,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},hn=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(hn||{}),dc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(dc||{}),lc=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))(lc||{}),uc=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(uc||{});var un=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(un||{});var cc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(cc||{});var vp=new ln(!0),qi=new ln(!1);var v=vp;var K={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Dp=new Map([[re,["Firefox",Fo]],[gr,["Edg",Go]],[Rr,["Chrome",sn]],[$e,["Safari",Ci]],[ht,["TBS",jo]],[Ts,["XWEB",qo]],[Tr&&Wi,["WeChat",Xo]],[Ss,["QQ(Win)",Qo]],[Ir,["QQ(Mobile)",_r]],[Sr,["QQ(Mobile X5)",_r]],[Is,["QQ(Mac)",zo]],[As,["QQ(iPad)",Yo]],[Rs,["MI",Ko]],[ys,["HW",Zo]],[bs,["Samsung",en]],[Ar,["OPPO",tn]],[Cr,["VIVO",rn]],[Er,["EDGE",Ho]],[Es,["SogouMobile",Wo]],[gs,["Sogou",Jo]]]);function Op(){let r=Dp.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var pc=function(){return!(Ha||Er||gr&&$a<80||re&&Ba<56)},jl=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},pn=function(){if(!navigator.mediaDevices)return di()||A.error(Ce.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},Jl=!1;function di(){return location.protocol==="http:"&&!ti?(Jl||A.error(x({key:L.NOT_SUPPORTED_HTTP})),Jl=!0,!0):!1}var Mp=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},mc=function(){return f(this,null,function*(){if(K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported)return{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),K.detail.isH264EncodeSupported=i,K.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},fn=function(){return f(this,null,function*(){if(K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return{isH264DecodeSupported:K.detail.isH264DecodeSupported,isVp8DecodeSupported:K.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},_n=rc(()=>f(void 0,null,function*(){if(K.result&&K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported&&K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return K;let r=Date.now(),i=pc(),e=Ec(),t=jl(),s=pn(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield mc(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield fn();if(!o||!n){let d=yield mc();A.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(d)}`),o=d.isH264EncodeSupported,n=d.isVp8EncodeSupported}if(o&&a&&(Ar||Cr||Wa)&&!ht&&ei()<79){let{encode:d,decode:u}=yield Lp();o=d,a=u}return K.result=i&&e&&s&&(o||n)&&(a||c),K.detail.isBrowserSupported=i,K.detail.isWebRTCSupported=e,K.detail.isWebCodecsSupported=t,K.detail.isMediaDevicesSupported=s,K.detail.isScreenShareSupported=$s(),K.detail.isSmallStreamSupported=Fs(),K.detail.isH264EncodeSupported=o,K.detail.isVp8EncodeSupported=n,K.detail.isH264DecodeSupported=a,K.detail.isVp8DecodeSupported=c,K.result||A.error(`${navigator.userAgent} ${ec(K.detail,!1)}`),Bp(),v.addNumber({key:523800,value:Date.now()-r}),K})),kp=function(){return K.result},$s=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},mn=null;function Lp(){return f(this,null,function*(){return mn||(mn=new Promise(r=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{A.warn("detectH264Supported start");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),d.close(),u.close(),c.getTracks().forEach(y=>y.stop())},a=setTimeout(()=>{e(),r(i)},2*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",y=>u.addIceCandidate(y.candidate)),u.addEventListener("icecandidate",y=>d.addIceCandidate(y.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield u.setRemoteDescription(m);let p=yield u.createAnswer(),_=hc.default.parse(p.sdp),C=_.media[0].rtp.findIndex(y=>y.codec==="H264");_.media[0].rtp=[_.media[0].rtp[C]],_.media[0].fmtp=_.media[0].fmtp.filter(y=>y.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(y=>y.payload===_.media[0].rtp[0].payload)),p.sdp=hc.default.write(_),yield u.setLocalDescription(p),yield d.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let y=yield d.getSenders()[0].getStats(),D=yield u.getReceivers()[0].getStats();i.encode||y.forEach(B=>{B.type==="outbound-rtp"&&B.mediaType===h.VIDEO&&B.bytesSent>0&&(i.encode=!0)}),i.decode||D.forEach(B=>{B.type==="inbound-rtp"&&B.mediaType===h.VIDEO&&B.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),A.warn(t),r(i)}})).then(r=>((!r.encode||!r.decode)&&A.warn(`detectH264Supported encode: ${r.encode} decode: ${r.decode} ${lt}`),r)),mn)})}var Pp=(r,i,e)=>{location.protocol==="http:"&&!ti&&(r[i]=()=>{throw new R({code:S.INVALID_OPERATION,message:Ce.NOT_SUPPORTED_HTTP})})},vi=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(le(r.selected)&&!r.selected):!1};function ql(){let r="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${i} * ${e}`}return r}function Xl(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ql(){let r={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){r.isSupported=!0;break}return r.isSupported}function zl(){return"captureStream"in HTMLCanvasElement.prototype}function Fs(){return Tr||Be||ft&&ft<63?!1:!!(pc()&&zl())}var xp=function(){if(g(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:Si}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function Xi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Di(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Pt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function tt(){return Ns===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Pr=(()=>!(!tt()||pt&&ft<86))();function wp(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function fc(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Hs(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Di()}var xt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,_c=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Tt="createEncodedStreams"in window.RTCRtpSender.prototype&&ei()>=86,En="RTCRtpScriptTransform"in window,Gs="RTCRtpSender"in window&&(Tt||En),Ec=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function gn(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(r.AudioDecoder=!0),g(window.AudioEncoder)||(r.AudioEncoder=!0),g(window.VideoDecoder)||(r.VideoDecoder=!0),g(window.VideoEncoder)||(r.VideoEncoder=!0),g(window.ImageDecoder)||(r.ImageDecoder=!0),r}function Yl(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function Kl(){return!g(window.WebTransport)}function Vp(){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 Up(){let r={browser:`${Nt.name}/${Nt.version}`,os:on(),displayResolution:ql(),isScreenShareSupported:$s(),isWebRTCSupported:Ec(),isGetUserMediaSupported:Xl(),isWebAudioSupported:Ql(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:gn(),isMediaSessionSupported:Yl(),isWebTransportSupported:Kl()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var Zl="checkResult";function Bp(){dn.setItem(Zl,{ua:navigator.userAgent,checkResult:K})}(function(){di();let i=dn.getItem(Zl);i&&i.ua===navigator.userAgent&&(K=i.checkResult),_n()})();function Qi(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var tu=Ie(Oe(),1);var eu=Symbol("instance"),mg=Symbol("abortCtrl"),Tn=Symbol("cacheResult"),Ws=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,qs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Js=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function $p(r){return typeof r=="object"&&r&&"then"in r}var js=new Map;function ue(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=js.get(t)||[];js.has(t)||js.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=F.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[Tn]:Promise.resolve(d[Tn]);d.state instanceof Ws&&d.state.action==e.abortAction&&d.state.abort(d);let u=null;Array.isArray(r)?r.length==0?d.state instanceof Ws&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(u=new Js(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(u=new Js(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`));let m=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 m(u);let p=d.state,_=new Ws(p,i,n);qs.call(d,_);let C=D=>{var B;return d[Tn]=D,_.aborted||(qs.call(d,i),(B=e.success)===null||B===void 0||B.call(this,d[Tn])),D},y=D=>{let B=D instanceof Error?D.message:String(D);return qs.call(d,p,D),m(new Js(d._state,`action '${n}' failed :${B}`,D instanceof Error?D:new Error(B)))};try{let D=a.apply(this,c);return $p(D)?D.then(C).catch(y):e.sync?C(D):Promise.resolve(C(D))}catch(D){return y(D)}}}}var Fp=(()=>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 qs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(F.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var F=class extends tu.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=F.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[eu];s?this.name=s.name+"-"+s.count++:t[eu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=js.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);js.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:u,action:m})=>{typeof d=="string"?s.push({from:d,to:u,action:m}):d.length?d.forEach(p=>{s.push({from:p,to:u,action:m})}):o.push({to:u,action:m})}),s.forEach(({from:d,to:u,action:m})=>{n.add(d),n.add(u),n.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${u} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),o.forEach(({to:d,action:u})=>{t.add(`${u}ing --> ${d} : ${u} \u{1F7E2}`),n.forEach(m=>{m!==d&&t.add(`${m} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=F.instances.get(i),e||F.instances.set(i,e=new F(i,void 0,Object.create(F.prototype)))):(e=F.instances2.get(i),e||F.instances2.set(i,e=new F(i.constructor.name,void 0,Object.create(F.prototype)))),e}static getState(i){var e;return(e=F.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Fp(F.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){qs.call(this,i)}};F.STATECHANGED="stateChanged";F.UPDATEAFSM="updateAFSM";F.INIT="[*]";F.ON="on";F.OFF="off";F.instances=new Map;F.instances2=new WeakMap;var iu=(window==null?void 0:window.requestIdleCallback)||function(r){let i=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},Hp=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Gp=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Xs=class{static generateTaskID(){return this.currentTaskID++}static run(i=Ai,e,t){i===Gi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===Ii?t=N({delay:1e4,count:0},t):i===fr?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),_t(e)&&(t=N(N({},t),e)),te(i)&&(e=i,i=Ai);let s=N({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(s.taskID,s),this[i](s),s.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.delay=(1e3/i.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
  14. let timerID = null;
  15. self.onmessage = function (e) {
  16. if (e.data === 'start') {
  17. timerID = setInterval(() => {
  18. self.postMessage('tick');
  19. }, ${i.delay});
  20. } else if (e.data === 'stop') {
  21. clearInterval(timerID);
  22. }
  23. };
  24. `],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=w(),t,s=()=>{if(t=w()-e,t>=i.delay&&(e=w()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=iu(s,{timeout:i.delay})};return i.ricID=iu(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=w(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=w()-e,e=w(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=w()-e,t>=i.delay&&(e=w()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let o=()=>{if(document.hidden){let n=w()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Gp(s),o&&Hp(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};Xs.taskMap=new Map,Xs.currentTaskID=1;var Z=Xs;var Tg={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:h.SEI_MESSAGE,ERROR:"error"};var Me={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Vt={};os(Vt,{create:()=>ke,remove:()=>_e});var Qs=new WeakMap;function ke(r,i){Qs.has(r)||Qs.set(r,[]);let e=Qs.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function _e(r){let i=Qs.get(r);i&&(i.forEach(e=>e()),Qs.delete(r))}var Ut=new WeakMap;function it({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=Ot({retryFunction:n.value,settings:r,onError({error:c,retry:d,reject:u,retryFuncArgs:m}){var p;i?i.call(this,c,()=>{var _;(_=Ut.get(s))!=null&&_.has(o)?d():u(c)},u,m):(p=Ut.get(s))!=null&&p.has(o)?d():u(c)},onRetrying(c,d){var u;Dt(e)&&e.call(this,c,d),(u=Ut.get(s))!=null&&u.has(o)&&(Ut.get(s).get(o).stopRetry=d)},onRetryFailed:t});return n.value=function(...c){let d=Ut.get(s);return d?d.set(o,{args:c}):Ut.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Ut.get(s))==null?void 0:u.delete(o)})},n}}function zs({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var c,d;if((c=Ut.get(t))!=null&&c.has(r)){let{stopRetry:u,args:m}=Ut.get(t).get(r),p=!0;if(e){for(let _ of m)if(!a.find(C=>C===_)){p=!1;break}}p&&(i&&i.apply(this,a),u&&u(),(d=Ut.get(t))==null||d.delete(r))}return n.apply(this,a)},o}}var Bt=class extends F{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"muted");l(this,"_log");l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_isReplayByRecreateMediaStreamCalled",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=ka,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 this.element.play()}catch(e){let t=x({key:L.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new R({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&Z.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():Ja?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 ke(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);Vt==null||Vt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){T.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&_e(this.track)}unbindEvents(){this.element&&_e(this.element),this.unbindTrackEvents(),T.off(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(Z.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),Be&&(this._interval=Z.run(Ai,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:s,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${o} userAgent: ${navigator.userAgent}`),Y.uploadEvent({log:`stat-${this.kind}-${Ue.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(Me.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Y.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),Y.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(Me.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,s)=>{Mr(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`),s((a=this.element)==null?void 0:a.error)}),Mr(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&s((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.handleStopped(h.ENDED);break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(Me.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Me.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Me.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};b([it({settings:{retries:2,timeout:0},onError(r,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],Bt.prototype,"doReplayByRecreateMediaStream",1),b([ue([],"PLAYING",{sync:!0})],Bt.prototype,"handlePlaying",1),b([ue("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Bt.prototype,"handlePaused",1),b([ue([],"STOPPED",{sync:!0})],Bt.prototype,"handleStopped",1);var li="trtc_autoplay",gc=`${li}_mask`,xr=`${li}_wrapper`,su=`${li}_header`,Tc=`${li}_content`,Sn=`${li}_action_wrapper`,Sc=`${li}_question`,Ic=`${li}_collapse`,In=`${li}_action_confirm`,ou=`${li}_detail`,nu="#2473E8",Cc="dialog",Wp=`${Cc}-show`,Jp=`${Cc}-1`,jp=`${Cc}-2`,au=!1,Rc=()=>!!document.querySelector(`.${xr}`),du=`${yt}/${vt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,cu=`<br><a href='${du}' target='_blank'>${vt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,qp=`${vt()?`\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${cu}`:`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. ${cu}`}`,Ac=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(vt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!au){let i=document.createElement("style");i.innerHTML=`.${gc}{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;}.${gc} div:not(.${Sn}){display:block !important;}.${xr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${xr} a{color:${nu};}.${su}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Tc}{margin:8px 0;}.${Sn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Ic}{margin-right:auto;cursor:pointer}.${Sc}{height:100%;line-height:16px;cursor:pointer;}.${In}{margin-left:8px;color:#fff;background:${nu};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${In}:hover{opacity:0.9;}.${Ic},.${In},.${Tc},.${Sc}{font-size:14px;}@media screen and (max-width:750px){.${xr}{width:80vw;}}`,document.head.appendChild(i),au=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${gc}"><div class='${xr}'><div class='${su}'>${location.host}</div><div class='${Tc}'>${this.content}</div><div class='${ou}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${qp}</div><div class='${Sn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=In,e.innerText=vt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Sc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
  25. <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">
  26. <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"/>
  27. <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"/>
  28. <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"/>
  29. </svg>
  30. `,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=Ic,s.innerText=`${vt()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${Sn}`);return n.appendChild(s),n.appendChild(t),n.appendChild(e),o}addDiaLog(){Rc()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${xr}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),Y.uploadEvent({log:Wp}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){A.warn("confirm clicked, try resume stream"),T.emit(E.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${ou}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Y.uploadEvent({log:Jp}),this._isCollapseClicked=!0}onQuestionClick(){window.open(du,"_blank"),this._isQuestionClicked||Y.uploadEvent({log:jp}),this._isQuestionClicked=!0}},lu=Ac;var je=class extends Bt{constructor(e){super(e,h.VIDEO);l(this,"viewMirror",!1);l(this,"objectFit");l(this,"container");l(this,"canvas");this.container=e.container,this.canvas=e.canvas,g(e.viewMirror)||(this.viewMirror=e.viewMirror),g(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!Rc()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let o=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=o.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!o.includes("scaleX")&&(this.element.style.transform=`${o} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(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(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Me.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function zi(r,i){return f(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),A.info("worklet addModule success")}catch(e){throw A.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Oi=new window.AudioContext({sampleRate:48e3}),An=()=>{Oi.state==="suspended"?(Oi.resume(),document.addEventListener("click",An)):Oi.state==="interrupted"?Oi.resume():document.removeEventListener("click",An)};document.addEventListener("click",An);Oi.onstatechange=()=>{A.info(`context state: ${Oi.state}`),An()};var uu=()=>Oi.state==="running",qe=r=>Oi;var St=class{constructor(){this.pre=new Set;this.next=new Set;this.connectedNodes=new Set;this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.node&&(this.node.channelCount=i),this.next.forEach(e=>e.channelCount=i)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(t){A.error(t),v.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){A.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},Cn=class extends St{constructor(e=256){super();this.fftSize=e;this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,s=0,o=0,n=`M${s},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${s},${o}`,s+=t;return n}},Ys=class{constructor(){this.source=new St;this.gain=new St;this.destination=new St}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(Xp(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}},wr=class extends Ys{constructor(e){super();this.context=e;this.denoiser=new St;this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},Rn=class{constructor(){this.audioContext=qe("audio-mixer");this.destination=this.audioContext.createMediaStreamDestination();this.inputs=new Set;this.mixWeight=0}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]}},hu=new WeakMap;function Xp(r){let i=hu.get(r);if(i)return i;let e=qe();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return hu.set(r,i),i}var Qp=`
  31. class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.cache=[];this.sentFirstInfo1=false;this.unmute=false;this.port.onmessage=(event)=>{const{data}=event;switch(data.name){case"chunk":this.cache.push.apply(this.cache,data.data);if(!this.sentFirstInfo1){this.port.postMessage({cl:data.data.length});this.sentFirstInfo1=true;}
  32. break;case"setIntervalTime":this.intervalTime=data.intervalTime;break;case"unmute":this.unmute=true;break;case"stop":this.isStop=true;break;}};}
  33. process(inputs,outputs){const input=inputs[0];const output=outputs[0];if(!input&&!output){return true;}
  34. if(this.isStop){return false;}
  35. const l=output?output[0].length:0;const cl=this.cache.length;if(cl>l){output[0].set(this.cache.slice(0,l));this.cache=this.cache.slice(l);}else if(this.unmute){output[0].set(input[0]);}
  36. const firstChannel=cl>l?output[0]:input[0];if(!firstChannel){return true;}
  37. let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i];}
  38. rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}
  39. return true;}}
  40. registerProcessor("volume-meter",VolumeMeter);
  41. `,Yi=class{constructor(i){l(this,"_volume",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Yi.workletReady||(Yi.workletReady=zi(Yi.audioContext,URL.createObjectURL(new Blob([Qp],{type:"application/javascript"})))),Yi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Yi.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Y.logFailedEvent({userId:this._log.userId,eventType:Ue.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ks=Yi;l(Ks,"audioContext",qe("volume-meter")),l(Ks,"workletReady");var yn=class extends St{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new Ks(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()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var _u=Ie(Oe(),1);var pu=r=>i=>i.deviceId===r;var Zs=class{constructor(i,e="Input"){l(this,"kind");l(this,"type");l(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Vr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(pu(s.deviceId))){let o=`${this.kind}${this.type}Added`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(pu(s.deviceId))){let o=`${this.kind}${this.type}Removed`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},yc=class extends _u.EventEmitter{constructor(){super();l(this,"audioInputs",new Zs(h.AUDIO));l(this,"videoInputs",new Zs(h.VIDEO));l(this,"audioOutputs",new Zs(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Gi,()=>{this.update()},{delay:1e4}))}init(){bn().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 bn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Se=ds||ur?null:new yc;function Vr(r){return r.deviceId===r.groupId&&r.groupId===""}function bn(){return f(this,arguments,function*(r=0){if(di()||!pn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Vr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&bc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Fe(r=!1){return Se.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return Se.update(r?2:0).then(i=>i.videoInputs.devices)}var fu=!1;function Eu(){return f(this,null,function*(){try{fu||(fu=!0,A.info(`speakers:${(yield Mi()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Mi(r=!1){return f(this,null,function*(){return Se.update(r?1:0).then(i=>i.audioOutputs.devices)})}var bc=new Set;function gu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!bc.has(t)}function Tu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!bc.has(t)}function Nc(r,i){return f(this,null,function*(){let t=(yield Fe()).find(s=>s.deviceId===Hi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function Su(o){return f(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Hi?yield Nc(e,t):!0})}var Nn,vc=class extends Ys{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeDestination");l(this,"analyser",new Cn);this.volumeMeter=new yn({log:this.log}),this.volumeDestination=new St,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Ur=class extends Bt{constructor(e){super(e,h.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",qe("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");this.pipeline=new vc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ri==="15.2"||Ri==="15.3"||Ri==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=Nn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===Nn&&(Nn=void 0),this.bindElementEvents()}play(){return f(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),Eu(),Ae(Ur.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},vn=class extends Ur{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Me.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Dn=class extends Ur{constructor(e){super(e);l(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Me.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._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),_e(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&yr&&(Nn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Ki=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Dn:je}){var a;super();l(this,"id",Us());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Me.PLAYER_STATE_CHANGED,c=>{T.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(Me.LOADED_DATA,()=>{T.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Me.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(u=>u.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(Me.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}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 s=fe(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 je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),fe(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===h.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),T.emit(E.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(),fe(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(le(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(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 je({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 s=[...this.subVideoPlayerMap.values()];for(let o of s)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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(gt(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.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()}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?E.TRACK_MUTED:E.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){ke(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_e(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,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 s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(gt(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(){if(this.room&&this.room.enableAutoPlayDialog)new lu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};b([ue([],F.INIT,{sync:!0})],Ki.prototype,"close",1);var zp=Object.prototype.hasOwnProperty,{toString:nS}=Object.prototype;function Yp(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(zp.call(r,i))return!1;return!0}}return!1}var Ft=Yp;var Kp=function(r){return f(this,null,function*(){let i=ef(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Fe(),A.info(`microphones: ${Et(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),A.info(`cameras: ${Et(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return _c&&o.getTracks().forEach(n=>{A.info(`${n.kind} capabilities: ${Et(n.getCapabilities(),{keysToInclude:$o})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=x({key:L.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=x({key:L.MICROPHONE_NOT_FOUND}))),new R({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Zp=Ot({retryFunction:Kp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!$e||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(r),t[0].microphoneId&&Iu(t[0].microphoneId,!1),t[0].cameraId&&Iu(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Y.logFailedEvent({eventType:Ue.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Y.logSuccessEvent({eventType:Ue.GET_USER_MEDIA_RETRY}),Y.uploadEvent({log:`stat-${Ue.GET_USER_MEDIA_RETRY}-success-${r}`})}});function Iu(r,i){return f(this,null,function*(){let t=(i?yield Xe():yield Fe()).find(s=>s.deviceId===r);t&&te(t.getCapabilities)&&A.warn(Et(t.getCapabilities(),{keysToInclude:$o}))})}function ef(r){return{audio:tf(r),video:rf(r)}}function tf(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Ft(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),le(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),le(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),le(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Ft(i)?!0:i)}function rf(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Ft(e)?e:(r.width&&(e.width={ideal:r.width},i&&!re&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!re&&(e.height.max=r.height)),re&&mt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Ft(e)?!0:e)}var Au=Zp;function On(r){return J((i,e)=>function(...t){return f(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function It(r){return J((i,e)=>function(...t){return f(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function J(r){return function(i,e,t){return t.value=r(t.value,e),t}}var Cu=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var sf=0,Mn=class{constructor(){this.log=A.createLogger({id:`fq${++sf}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(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(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},to=new WeakMap,kn=new WeakMap;function Ht(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=to.get(this)||new Mn;return to.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function Ru(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=to.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let u=!0;return c.args.forEach(m=>{o.find(p=>p===m)||(u=!1)}),u?(c.reject(new R({code:S.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Ln(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=to.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(d=kn.get(this))==null||d.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new R({code:S.API_CALL_ABORTED,message:r}))}),to.delete(this),kn.delete(this),s.apply(this,o)},t}}function ui(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=kn.get(this)||new Map,c=a.get(o(n))||new Mn;return a.set(o(n),c),kn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Dc=class extends Ki{constructor(e,t){super({mediaType:e,PlayerClass:t});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){ke(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_e(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let s=w();T.emit(E.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 Au(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:w()-s}),o}catch(s){throw T.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),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(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&xt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield Su({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),bn().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!Tu(this.mediaTrack)||this.kind===h.VIDEO&&!gu(this.mediaTrack)||this._isRecapturing||e&&mt&&$e)}onTrackMuted(){if(super.onTrackMuted(),Cu(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<pr){setTimeout(()=>this.onTrackMuted(),pr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Be||pe)&&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(Ae(Dc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<pr){setTimeout(()=>this.onTrackEnded(),pr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Fe():yield Xe()).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(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),T.emit(E.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 s=(io.get(t)||0)+1;if(io.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!io.has(n.deviceId)):(yield Fe()).find(n=>!io.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} 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)}},Qe=Dc;b([ue(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),b([Ht()],Qe.prototype,"capture",1),b([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.kind===h.AUDIO,i=this.stat.bytesSent>0;v[i?"addSuccessEvent":"addFailedEvent"]({key:r?503700:513702}),i||(v.addEnum({key:r?503701:513703,value:Ds()}),Y.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ji()||ri()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),b([J(r=>function(){return f(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ue([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var io=new Map;T.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&io.delete(r.track.deviceId)});var Le=class extends Qe{constructor(e){super(1,vn);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new wr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){yield Ae(Le.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return f(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Hi){if(yield Nc(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}),this.room&&(yield this.room.replaceTrack(this)),T.emit(E.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(){Se&&!Se.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Se.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)}`),ce(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Fe();t[0]?this.recapture(t[0].deviceId):Se.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:s}){let n=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!g(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(ft<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),Se.off("audioInputAdded",this.handleMicrophoneAdded,this),Se.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ae(Le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Fe()).find(o=>o.deviceId!==e);if(s)yield Ae(Le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce((t,s)=>s?s({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var hi=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var Pn=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hi(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)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),u=new DataView(i.data),m=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)d.setInt8(m++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,u.getInt8(p));return i.data=c,n.length}return 0}};var he=class extends Qe{constructor(e,t=4){super(t,je);l(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new Pn);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!xt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,s,o;if(z(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ae(he.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ae(he.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!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:s,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&pt&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ja&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:tc()&&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),T.emit(E.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(){Se&&!Se.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Se.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)}`),ce(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Xe();t[0]?this.recapture(t[0].deviceId):Se.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 s=t?8:this.mediaType;return this.manager.encodePipeline.reduce((o,n)=>n?n({frame:o,mediaType:s}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return f(this,null,function*(){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ae(he.prototype,this,"play").call(this,e,t)})}close(){Se.off("videoInputAdded",this.handleCameraAdded,this),Se.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ae(he.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ae(he.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var vu=Us();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:vu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var df=function(r){return f(this,null,function*(){let i=null,e=hf(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Rr&&ft<74||$e||re)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){A.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield lf(s,r.captureElement))}if(r.audio){let o=uf(r);A.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function lf(r,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&te(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===vu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function uf(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return g(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function hf(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:$e?{max:r.width}:{ideal:r.width,max:r.width},height:$e?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var Du=df;var ze=class extends he{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):m=yield Du({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof R?m:new R({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};var Gt=class extends Le{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var mf="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Oc;function Mc(r){return f(this,null,function*(){let i=qe("dump");Oc||(Oc=zi(i,URL.createObjectURL(new Blob([mf],{type:"application/javascript"})))),yield Oc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var xn=class extends Rn{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",A.createLogger({id:"am"}));l(this,"denoiser");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],s=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let 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 p=0;p<s.length;p++){let _=URL.createObjectURL(new Blob(n[p])),C=document.createElement("a");C.href=_,C.download=`${s[p]}.pcm`,C.style.display="none",document.body.appendChild(C),C.click(),URL.revokeObjectURL(_),C.remove()}clearTimeout(a),o.abort("download")},d=Mc(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((C,y)=>n[y]=n[y]?n[y].concat(C[0]):[C[0]])}}),o).catch(_=>c));return{then:d.then.bind(d),download:c}}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}let t=new Float32Array(1920),s=0,o=new AbortController;return Mc([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){t.set(c[0][0],s),s+=c[0][0].length,s>=1920&&(s=0,e(t),t=new Float32Array(1920))}}),o).catch(c=>this.log.error(`stop getPCM reason:${c}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Gt)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Le)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof mi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Gt?delete this._localScreenAudioTrack:e instanceof Le?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)}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function wn(r=30,i=2){return J((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new R({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var kc=class extends Ki{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===kc.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},rt=kc;l(rt,"STATE_SUBSCRIBE","subscribe"),b([wn(5,1)],rt.prototype,"waitHasMediaTrack",1),b([ue(F.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.kind===h.AUDIO,i=this.player.isPlaying||(r?this.getAudioLevel()>0:this.stat.framesDecoded>0);v[i?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),i||(v.addEnum({key:r?504701:514703,value:Ds()}),Y.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ji()||ri()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`))}},5e3)},ignoreError:!0})],rt.prototype,"subscribe",1),b([ue(rt.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],rt.prototype,"unsubscribe",1);var mi=class extends rt{constructor(e,t){super(e,t,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});l(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this._log.warn("use audio decoder"),this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(s=>s)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&gn().AudioDecoder&&Tt:!1}decodeFrame(e){var s;if(!this.manager)return e;let t=this.manager.decodePipeline.reduce((o,n)=>n?n({frame:o}):o,e);return((s=this.audioDecoder)==null?void 0:s.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"})),t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var ff=[-1,-1,1,-1,-1,1,1,1],_f=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");l(this,"log");if(this.context.on("disconnect",this.close,this),this.name=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){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(_f),this.positionBuffer=this.createBuffer(ff),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${s.message||s}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof be&&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(){var e;(e=this.output)==null||e.update()}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 be){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),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 s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),u=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:u,name:a,cost:c},N({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([ue(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),b([ue("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),b([ue([],"closed",{sync:!0})],Ye.prototype,"close",1);function se(...r){}var Ef=r=>r();function xc(){this.dispose()}var gf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Tf=1,Wt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Pc(i,this,this.streamId++);return Ee.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Br=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=se,this.error=se,this.next=se,this.dispose=se,this.subscribe=se,this.doDefer()}subscribe(i){return i instanceof Wt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Ef),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}},H=class extends Br{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)}},Vn=class extends Br{constructor(i,e=se,t=se,s=se){if(super(),this._next=e,this._error=t,this._complete=s,this.then=se,i instanceof Wt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ee.defer(o,0)}),Ee.create(o),Ee.pipe(o),this.sourceId=o.id,this.subscribe(i),Ee.subscribe({id:o.id,end:!0}),e==se?this._next=n=>Ee.next(o,0,n):this.next=n=>{Ee.next(o,0,n),e(n)},s==se?this._complete=()=>Ee.complete(o,0):this.complete=()=>{this.dispose(),Ee.complete(o,0),s()},t==se?this._error=n=>Ee.complete(o,0,n):this.error=n=>{this.dispose(),Ee.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 $r(r,...i){return i.reduce((e,t)=>t(e),r)}function st(r,i,e){if(gf()){let t=Object.defineProperties(Object.setPrototypeOf(r,Wt.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}});Ee.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof Wt&&Ee.addSource(t,o)}return t}return r}function j(r,i){return function(...e){return t=>{if(t instanceof Wt){let s=st(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,Ee.pipe(s),s}else return s=>t(new r(s,...e))}}}function Li(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var Pc=class extends H{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ee.defer(this.source,this.id)})}next(i){Ee.next(this.source,this.id,i),this.sink.next(i)}complete(){Ee.complete(this.source,this.id),this.sink.complete()}error(i){Ee.complete(this.source,this.id,i),this.sink.error(i)}},Ee={addSource(r,i){Li("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Li("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Li("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Li("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Li("defer",{id:r.id,streamId:i})},pipe(r){Li("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Li("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=Tf++),Li("create",{name:r.toString(),id:r.id})}},Un=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var wc=class extends Br{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 Bn(){return r=>{let i=new wc(r);if(r instanceof Wt){let e=st(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Ee.pipe(e),e}return st(i.add.bind(i),"share",arguments)}}function Sf(...r){return st(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(c,d)=>{let u=new H(i);u.next=m=>{--t===0?(u.next=p=>{o[d]=p,i.next(o)},u.next(m)):o[d]=m},u.complete=n,u.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Vc=class extends H{constructor(i,...e){super(i);let t=new H(this.sink);t.next=s=>this.buffer=s,t.complete=se,t.subscribe(Sf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},KA=j(Vc,"withLatestFrom"),Uc=class extends H{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()}},ZA=j(Uc,"bufferCount"),Bc=class extends H{constructor(i,e){super(i),this.buffer=[];let t=new H(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=se,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},eC=j(Bc,"buffer");function Fc(r){let i=arguments,e=Bn()(st(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=se,e.complete=se,e.error=se,e}function Ou(r){return st(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function $c(r,i){return e=>{let t=s=>e.next(s);e.defer(()=>i(t)),r(t)}}function ro(r,i){if("on"in r&&"off"in r)return st($c(e=>r.on(i,e),e=>r.off(i,e)),"fromEvent",arguments);if("addListener"in r&&"removeListener"in r)return st($c(e=>r.addListener(i,e),e=>r.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in r)return st($c(e=>r.addEventListener(i,e),e=>r.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}var Hc=class extends H{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},If=j(Hc,"reduce");var Gc=class extends H{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Af=j(Gc,"filter"),Wc=class extends H{next(i){}},uC=j(Wc,"ignoreElements"),Jc=class extends H{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Mu=j(Jc,"take"),jc=class extends H{constructor(i,e){super(i);let t=new H(i);t.next=()=>i.complete(),t.complete=xc,t.subscribe(e)}},nd=j(jc,"takeUntil"),qc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Cf=j(qc,"takeWhile");var Xc=class extends H{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},hC=j(Xc,"skip"),Qc=class extends H{constructor(i,e){super(i),i.next=se;let t=new H(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=xc,t.subscribe(e)}},mC=j(Qc,"skipUntil"),zc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ku=j(zc,"skipWhile"),Rf={leading:!0,trailing:!1},Yc=class extends H{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)}},Kc=class extends H{constructor(i,e,t=Rf){super(i),this.durationSelector=e,this.config=t,this._throttle=new Yc(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=se,this._throttle.complete(),super.complete()}},pC=j(Kc,"throttle");var Zc=class extends H{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},ed=class extends H{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Zc(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()}},fC=j(ed,"debounce");var td=class extends H{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()}},_C=j(td,"elementAt");var id=class extends H{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}},EC=j(id,"findIndex"),rd=class extends H{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()}},gC=j(rd,"first"),sd=class extends H{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()}},TC=j(sd,"last"),od=class extends H{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()}},SC=j(od,"every");var ad=class extends H{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},RC=j(ad,"scan"),cd=class extends H{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},yC=j(cd,"pairwise"),dd=class extends H{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Lu=j(dd,"map");var Fr=class extends H{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()}},Hr=class extends H{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()}},$n=class extends Fr{},Fn=class extends Hr{next(i){this.subInner(i,$n),this.next=e=>{this.currentSink.dispose(),this.subInner(e,$n)}}},yf=j(Fn,"switchMap");function Jn(r){return(i,e)=>r(()=>i,e)}var Pu=Jn(j(Fn,"switchMapTo")),ld=class extends Fr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Hn=class extends Hr{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(),ld),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},bC=j(Hn,"concatMap"),NC=Jn(j(Hn,"concatMapTo")),ud=class extends Fr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Gn=class extends Hr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,ud),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},vC=j(Gn,"mergeMap"),DC=Jn(j(Gn,"mergeMapTo")),hd=class extends Fr{dispose(){this.context.resetNext(),super.dispose()}},Wn=class extends Hr{next(i){this.next=se,this.subInner(i,hd)}},OC=j(Wn,"exhaustMap"),MC=Jn(j(Wn,"exhaustMapTo")),md=class extends H{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=Fc(),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)}},kC=j(md,"groupBy"),pd=class extends H{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}},LC=j(pd,"timeInterval"),fd=class extends H{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()}},PC=j(fd,"bufferTime"),_d=class extends H{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},xC=j(_d,"delay"),Ed=class extends H{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},wC=j(Ed,"catchError");var jn=(r=se,i=se,e=se)=>t=>new Vn(t,r,i,e),gd=class extends H{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)}))}},BC=j(gd,"tap"),Td=class extends H{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Un(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},$C=j(Td,"timeout");var bf=$r(Ou(250),Lu(()=>performance.now()),Bn());var xu=r=>i=>{let e=performance.now();$r(bf,ku(t=>t-e<r),Mu(1))(i)};var Nf=[0,1,1,1,0,0,1,0],so=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);e instanceof Ge?this.ctx2d=e.ctx||null:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Nf)}start(e){this.log.info(`${this.name} start render ${e} fps`),this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof be){let s=this.context.ctx.getError();s&&this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(){if(this._intervalId){this.log.info(`${this.name} use requestVideoFrameCallback`),Z.clearTask(this._intervalId),this._intervalId=0;let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Gr=class extends so{constructor(e,t){super(e,t);l(this,"_videoTrack");l(this,"_muteOb");l(this,"_closedOb",ro(this,"closed"));l(this,"_subscription");l(this,"_canvasContainer");Number(Ci)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ro(this._videoTrack,"mute"),$r(ro(this._videoTrack,"ended"),nd(this._closedOb),jn(()=>{this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=$r(this._muteOb,nd(this._closedOb),Pu(xu(5e3)),jn(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new R({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()}},qn=class extends Gr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Xn=class extends Gr{constructor(e,t,s){super(e,{name:"smallDestination",logger:s});this.resolution=t}resize(e,t){let s,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?s=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}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var oo=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){let{width:s,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(Qi()&&!document.hidden&&n.requestVideoFrameCallback((a,c)=>{document.hidden||(this._totalFrames=c.presentedFrames,this.update())}),{videoWidth:s,videoHeight:o}=n,!s||!o)return!1;n.width=s,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:s,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(s===this.width&&o===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&({width:s,height:o}=n,this._lastImage=n);if(!this._autoResize)return!0;if(this.width===s&&this.height===o&&this.totalFrames){if(t){this.useTexture();let a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,n)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},no=class extends oo{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},Wr=class extends no{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Df=`
  42. // \u9876\u70B9\u7740\u8272\u5668
  43. attribute vec4 a_position;
  44. attribute vec2 a_texCoord;
  45. varying vec2 v_texCoord;
  46. void main() {
  47. gl_Position = a_position;
  48. v_texCoord = a_texCoord;
  49. }
  50. `,Of=`
  51. // \u7247\u5143\u7740\u8272\u5668
  52. precision mediump float;
  53. varying vec2 v_texCoord;
  54. uniform sampler2D u_texture;
  55. void main() {
  56. gl_FragColor = texture2D(u_texture, v_texCoord);
  57. } `;var Zi=class extends F{constructor(e){super();l(this,"frameRate");l(this,"_canvas");l(this,"log");l(this,"hasAlpha",!1);l(this,"name");l(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wr(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Gr(this,e)}createVideoImageSource(e,t){return new oo(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new no(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};l(Zi,"_ids",0);var Mf={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},be=class extends Zi{constructor(){super(...arguments);l(this,"defaultProgam");l(this,"defaultVShader");l(this,"defaultFShader");l(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Zi._ids++}`),this.ctx=this._canvas.getContext("webgl2",Mf),!this.ctx)throw new R({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Df),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Of),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.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 s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,o=s.createShader(e);return s.shaderSource(o,t),s.compileShader(o),o}createProgram(e,t){let s=this.ctx,o=s.createProgram();return s.attachShader(o,e),s.attachShader(o,t),s.linkProgram(o),s.getProgramParameter(o,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(o)),o}};b([ue(F.INIT,"created",{sync:!0,fail(r){v.addFailedEvent({key:512700,error:r.cause})},success(){v.addSuccessEvent({key:512700})}})],be.prototype,"create",1),b([ue("created",F.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],be.prototype,"destroy",1);var Ge=class extends Zi{constructor(){super(...arguments);l(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Zi._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new R({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,v.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(),v.addSuccessEvent({key:512703})}};b([ue(F.INIT,"created",{sync:!0,fail(r){v.addFailedEvent({key:512701,error:r.cause})},success(){v.addSuccessEvent({key:512701})}})],Ge.prototype,"create",1),b([ue("created",F.INIT,{ignoreError:!0,sync:!0})],Ge.prototype,"destroy",1);function kf(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var At=class extends rt{constructor(e,t,s=4){super(e,t,s);l(this,"mediaType",4);l(this,"source");l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}play(e,t){return(le(t==null?void 0:t.canvasRender)?t.canvasRender:Ns===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!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=e.createVideoPlayerSource(this.player);this.source=t;let s=new so(e,{name:"remotePlayer",logger:this.log});t.connect(s),this.player.setCanvas(e._canvas),Qi()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,s=kf(t);if(!ee(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(s===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${s} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${s}, current: ${e.frameRate}`),e.frameRate=s}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 s=e.find(a=>a.uint32_video_stream_type===t);return(s==null?void 0:s.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager?this.manager.decodePipeline.some(e=>e):!1}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce((t,s)=>s?s({frame:t,track:this}):t,e):e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Jr=class extends At{constructor(e,t){super(e,t,2);l(this,"mediaType",2);l(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};var jr=new Map;T.on(E.JOIN_SUCCESS,({room:r})=>{ce(r.userId,{eventId:32788})});T.on(E.LEAVE_START,({room:r})=>{ce(r.userId,{eventId:32789})});T.on(E.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ce(r.room.userId,{eventId:i})}});T.on(E.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ce(r.room.userId,{eventId:i})}});T.on(E.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ce(r.room.userId,{eventId:r.isRemote?32785:32772,remoteUserId:r.isRemote?r.userId:void 0}):ce(r.room.userId,{eventId:r.isRemote?32784:32773,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(E.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ce(r.room.userId,{eventId:r.isRemote?32787:32774,remoteUserId:r.isRemote?r.userId:void 0}):ce(r.room.userId,{eventId:r.isRemote?32786:32775,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(E.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ce(r.room.userId,{eventId:32777,remoteUserId:r.userId}),r.mediaType===4&&ce(r.room.userId,{eventId:32776,remoteUserId:r.userId}),r.mediaType===8&&ce(r.room.userId,{eventId:32803,remoteUserId:r.userId}))});T.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ce(r.room.userId,{eventId:32779,remoteUserId:r.userId}),r.mediaType===4&&ce(r.room.userId,{eventId:32778,remoteUserId:r.userId}),r.mediaType===8&&ce(r.room.userId,{eventId:32804,remoteUserId:r.userId}))});T.on(E.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ce(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});T.on(E.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ce(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});T.on(E.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,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&&ce(r.userId,{eventId:t})});T.on(E.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=s?32801:32798:o=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799);break;case"RECONNECTING":o=s?32800:32797;break}o&&ce(r.userId,{eventId:o,remoteUserId:t})});T.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:o})=>{let n=t?1:0;s||(n=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:n,param2:a,streamType:o||2};i&&(c.remoteUserId=i,c.eventId=4005),ce(r,c),v.addEnum({key:i?514701:513701,value:n}),v.addEnum({key:i?514700:513700,value:a})});T.on(E.LOCAL_TRACK_RECAPTURE,({track:r,error:i})=>{if(r.userId){let e={eventId:2003,param1:0};r.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=r.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ce(r.userId,e)}});function ce(r,i){let e=P(N({},i),{timestamp:as()});jr.has(r)?jr.get(r).push(e):jr.set(r,[e])}function wu(r){if(jr.has(r)){let i=jr.get(r).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 jr.delete(r),i}return[]}var Vu=Ie(Oe(),1);var Qn=class extends Vu.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;l(this,"userMap",new Map);l(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let o=`peer leave [${e}]`;g(t)||(o+=`:${La[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let s=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let s=t[this.key];if(s===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=Ni(o,n),d=(u=this.remotePublishedUserMap.get(s))==null?void 0:u.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==o&&(m.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,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:Ni(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Sd({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return J((t,s)=>{let o=new Map;return T.on(E.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new R({code:S.INVALID_OPERATION,message:x({key:L.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var Uu=!0,Bu=function(){var r;Uu&&(Uu=!1,A.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${yt}/en/index.html`),console.info(`* Changelog: ${yt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),A.info("TRTC Web SDK Version:",ye),A.info("UA:",navigator.userAgent),A.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),vs().then(i=>{i&&A.info(lt)}))};var ot={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"};var 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},Ct=(I=>(I[I.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",I[I.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",I[I.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",I[I.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",I[I.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",I[I.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",I[I.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",I[I.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",I[I.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",I[I.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",I[I.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",I[I.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",I[I.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",I[I.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",I[I.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",I[I.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",I[I.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",I[I.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",I[I.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",I[I.INVALID_OPERATION=5100]="INVALID_OPERATION",I[I.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",I[I.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",I[I.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",I[I.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",I[I.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",I[I.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",I[I.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",I[I.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",I[I.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",I[I.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",I[I.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",I[I.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",I[I.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",I[I.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",I[I.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",I[I.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",I[I.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",I[I.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",I[I.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",I[I.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",I[I.DEVICE_ERROR=5300]="DEVICE_ERROR",I[I.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",I[I.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",I[I.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",I[I.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",I[I.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",I[I.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",I[I.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",I[I.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",I[I.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",I[I.SERVER_ERROR=5400]="SERVER_ERROR",I[I.NEED_TO_BUY=5401]="NEED_TO_BUY",I[I.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",I[I.OPERATION_FAILED=5500]="OPERATION_FAILED",I[I.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",I[I.REJOIN_FAILED=5502]="REJOIN_FAILED",I[I.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",I[I.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",I[I.OPERATION_ABORT=5998]="OPERATION_ABORT",I[I.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",I))(Ct||{});function Fu({code:r,params:i,enableDocLink:e=!1}){let t="",s,o=Ct[r];try{s=$u[o]}catch(n){s=$u.UNKNOWN_ERROR}return te(s)?t=s(i):z(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var $u=P(N({},Ce),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${ge(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${ge(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' 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:r})=>`you need to call ${r}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:i=er(r),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function er(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var tr=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:o,fnName:n="",originError:a}){var d;let c;s?c=s:c=Fu({code:t||e,params:N({fnName:n,error:a},o)});super(c);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"handler");l(this,"originError");this.name=Ct[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");Zt?p.href=`ms-settings:privacy-${m[this.functionName]}`:mt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,s){let o=e;if(e instanceof R){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(Ce.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=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=Lf(e.name));break;case S.UNKNOWN:break;default:a.code=V.OPERATION_FAILED}o=new tr(a),n&&(o.stack+=n.substr(n.indexOf(`
  58. `)))}else{if(e instanceof tr)return e;o=new tr({code:V.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function Lf(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var k=tr;var Hu={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}}},Gu={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}}},qr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:V.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Wu={name:"userId",required:!0,type:"string"},Ju={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ot.AUDIO_PROFILE_STANDARD,ot.AUDIO_PROFILE_STANDARD_STEREO,ot.AUDIO_PROFILE_HIGH,ot.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function lo(r,i){if(!r)throw new k({code:V.INVALID_OPERATION,extraCode:5101,fnName:i})}function ju(r,i,e){if(!r)throw new k({code:V.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var bb={type:"number",notLessThanZero:!0},Pf={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new k({code:V.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:V.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:V.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new k({code:V.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({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"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:qr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Hu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&di())throw new k({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},qr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Hu}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Ju},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&di())throw new k({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Ju}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:qr,publish:{type:"boolean"},option:Gu},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&di())throw new k({code:V.ENV_NOT_SUPPORTED,extraCode:5201});if(!$s())throw new k({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:qr,publish:{type:"boolean"},option:Gu}},muteRemoteAudio:[Wu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Wu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:qr,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){lo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(ju(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},qr),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){lo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(ju(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&g(r.streamType))throw new k({code:V.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){lo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Gs)throw new k({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:V.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:V.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});lo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({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(r,i,e,t){if(r.byteLength>1e3)throw new k({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:V.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(lo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:V.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Re={TRTC:Pf};var Pe=class extends Error{};function xf(r,i){let e=Dr(r);for(let t=0;t<i.length;t++)ni(e[t],i[t]);return e}function wf(r){this._resolve=Promise.resolve(r)}function Vf(r){this._reject=Promise.reject(r)}var ir=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=xf;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),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Pe("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:wf,reject:Vf};try{switch(this.state){case 1:if(i===0)throw new Pe("already started");break;case 4:if(i===2)throw new Pe("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Pe("already start");break;case 3:switch(i.type){case 2:throw new Pe("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Pe("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Pe("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new Pe("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Pe("start not allowed after update");case 0:throw new Pe("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Pe("keep start")),new Pe("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Jt=ir;Jt.instances=new WeakMap;var Yn=new WeakMap,Kn=(r,i)=>{if(i instanceof Pe){let{stack:e}=i;i=new k({code:V.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
  59. `)))}throw i};function Pi(r,i){return J((e,t)=>function(...s){let o=Jt.get(this,typeof r=="string"?r:r.call(this,...s));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Kn.bind(null,t))):e.apply(this,s)})}function rr(r,i){let{merge:e,debounce:t}=i||{};return J((s,o)=>function(...n){let a=Jt.get(this,typeof r=="string"?r:r.call(this,...n));if(!a)return s.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=t;return new Promise((u,m)=>{var C,y;let p=(C=Yn.get(this))==null?void 0:C.get(d(...n));if(p){let{timeoutId:D,resolve:B}=p;clearTimeout(D),B()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,s.bind(this),n).catch(Kn.bind(null,o)).then(u,m)},c);Yn.has(this)?(y=Yn.get(this))==null||y.set(d(...n),{timeoutId:_,resolve:u}):Yn.set(this,new Map([[d(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,s.bind(this),n).catch(Kn.bind(null,o))})}function xi(r){return J((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Jt.gets(this,s).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Jt.get(this,s);return o?o.action(3,i.bind(this),t).catch(Kn.bind(null,e)):i.apply(this,t)})}var M={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"},qu=new Set([M.ERROR,M.AUTOPLAY_FAILED,M.KICKED_OUT,M.REMOTE_USER_ENTER,M.REMOTE_USER_EXIT,M.REMOTE_AUDIO_AVAILABLE,M.REMOTE_AUDIO_UNAVAILABLE,M.REMOTE_VIDEO_AVAILABLE,M.REMOTE_VIDEO_UNAVAILABLE,M.CONNECTION_STATE_CHANGED,M.PUBLISH_STATE_CHANGED,M.SCREEN_SHARE_STOPPED,M.DEVICE_CHANGED]);function uo(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function sr(r){return r===ot.QOS_PREFERENCE_CLEAR?"detail":r===ot.QOS_PREFERENCE_SMOOTH?"motion":""}var Uf=r=>r.startsWith("data:application/octet-stream;base64,"),Bf=r=>r.startsWith("file://"),Zn=class{constructor(){l(this,"_log");this._log=A.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};try{let s=w(),o;if(te(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=w()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:w()-s}),o.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),v.addFailedEvent({key:522700,error:s}),s}})}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 s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{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}):s(new Error("XHR failed"))},o.onerror=s,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=w(),s=null,o=null;if(te(WebAssembly.instantiateStreaming)&&!Uf(i)&&!Bf(i)&&te(fetch))try{let n=fetch(i);s=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!s)try{let n=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(s){let n=w()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),v.addFailedEvent({key:522701,error:o}),o})}};b([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Zn.prototype,"download",1);var Xu=new Zn;function Qu({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Xu,innerEmitter:T,constants:Pa,environment:br,utils:Ve,eventLogger:Y,log:this.room.getLogger(),loggerManager:A,errorModule:e,kvStatManager:v,rtcDectection:wt,trtc:this,clearStarted:(s,o)=>{let n=s.getAlias(),a=Jt.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})}}}var zu=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=x({key:L.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${o}
  60. ${s.stack}`),!1}},r};var ea=new WeakMap;function Yu(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=ea.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);ea.has(this)?(c=ea.get(this))==null||c.set(i(...s),n):ea.set(this,new Map([[i(...s),n]]))})}var Ku="5.8.3";function xe(...r){return J((i,e)=>function(...t){try{ia.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Cd(...r){return J((i,e)=>function(...t){try{ia.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function ia(r,i,e,t){if(fe(r))for(let s=0;s<r.length;s++)ta.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else ta.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function ta({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:V.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new k(o(5001));if(g(r.defaultValue)){te(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),te(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&ge(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:V.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ps(d)?nn(d):z(d)?d:ge(d))},value:i}})}else if(!g(r.type)&&ge(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!g(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!g(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(te(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&_t(i)&&Object.keys(n).forEach(c=>{ta.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&fe(i)&&i.forEach((c,d)=>{ta.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),te(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(u,m,p){if(p&&p.includes(u))return"hided";if(e){let _=e(...n);if(n[_.argIndex]===m)return _.value}if(m===n||u in n)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${ge(m)}`:(JSON.stringify(m),m)}catch(_){return`type:${ge(m)}`}}let c=this._log||A;n.length>0?c.info(`${o}() ${JSON.stringify(n,(u,m)=>a(u,m,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):hn[o];try{let u=s.apply(this,n),m=w();return Ls(u)?u.then(p=>(c.info(`${o}() success ${i.call(this,...n)}`),v.addSuccessEvent({key:d,cost:w()-m}),p)).catch(p=>{throw p=k.convertFrom.call(this,p,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${p} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:p}),p}):(v.addSuccessEvent({key:d}),u)}catch(u){throw u=k.convertFrom.call(this,u,o),c.error(`${o}() failed ${u} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:u}),u}})}var ra=r=>J((i,e)=>function(t,s){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:V.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(te(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:V.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return ia.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var sa=0,Rd=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new wr(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 Xr(r,i){if(i&&typeof i!="function")throw new k({code:V.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Qr=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);sa=sa+1,this.log=i.log.createChild({id:`${this.getAlias()}${sa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${sa}`),this.core=i}getName(){return Qr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Qr.startValidateRule;case"update":return Qr.updateValidateRule;case"stop":return Qr.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:s}=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 Rd(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.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:s,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(s)||n.seek(s),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:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:u}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),s&&v.addCount({key:502704}),o&&v.addCount({key:502705}),n&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof c!="function"&&v.addCount({key:502709}),typeof u!="function"&&v.addCount({key:502710}),typeof d!="function"&&v.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()}},wi=Qr;l(wi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({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 k({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Xr("onTimeUpdate",i.onTimeUpdate),Xr("onEnded",i.onEnded),Xr("onDurationChange",i.onDurationChange)}}),l(wi,"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){Xr("onTimeUpdate",i.onTimeUpdate),Xr("onEnded",i.onEnded),Xr("onDurationChange",i.onDurationChange)}}),l(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(wi,"Name","AudioMixer");var Ff=r=>(r=Number(r),r>0&&r<14e8),oa=0,yd,zr=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");oa=oa+1,this.log=i.log.createChild({id:`${this.getAlias()}${oa}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${oa}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:V.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return yd||(yd=this.doPreload(i)),yd}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield zi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return zr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return zr.startValidateRule(this.core);case"update":return zr.updateValidateRule;case"stop":return zr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield Gf(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:V.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return 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(){}},or=zr;l(or,"updateValidateRule",{type:"object"}),l(or,"stopValidateRule",{type:"object"}),l(or,"Name","AIDenoiser");var Zu={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Hf(r){let i;return Ff(r)?i=Zu.MAIN_OVERSEA:i=Zu.MAIN,i}function Gf(s){return f(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${Hf(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var eh=Ie(Oe(),1);var bd=class extends eh.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Y.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&A.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Y.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},Wf=new bd,Nd=Wf;function vd([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hi(new DataView(new Uint8Array(o).buffer),!0)}function Dd(r){return r.type==="empty"||r.data.byteLength===0}function Od(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Md(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function kd({frame:r,seiMessageList:i}){if(!i||i.length===0||r.data.byteLength===0)return r;let e=Md(r.data),t=9-e;if(t<=0)return r;let s=i.splice(0,t).reverse().map(vd),o=s.reduce((u,m)=>u+m.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let u=0;u<s.length;u++)for(let m=0;m<s[u].dataView.byteLength;m++)a.setInt8(d++,s[u].dataView.getInt8(m));for(let u=0;u<r.data.byteLength;u++)a.setInt8(d++,c.getInt8(u));return r.data=n,r}function Ld({frame:r,onSEI:i}){try{let e=new DataView(r.data);if(Dd(r)||!Od(e))return r;let t=[],s=0,o=-1,n=-1;for(let a=0;a<r.data.byteLength;a++){let c=e.getUint8(a);if(c===0)s++;else if(c===1){if(s===2||s===3){let d=a-s;if(o===-1?o=d:n===-1&&(n=d,t.push(new hi(new DataView(e.buffer.slice(o,n)))),o=d,n=-1),!(e.getUint8(a+1)===6)){r.data=e.buffer.slice(d);break}}s=0}else s=0}i==null||i(t.reverse())}catch(e){}return r}var Pd=0,xd=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Pd++,this.log=i.log.createChild({id:`${this.getAlias()}${Pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${Pd}`),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 kd({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ld({frame:i,onSEI:t=>{t.forEach(s=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:s.seiPayloadType,data:s.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:Tt?this.encode:kd,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:Tt?this.decode:Ld,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:s})}getName(){return xd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},Yr=xd;l(Yr,"autoStart",!0),l(Yr,"Name","SEI");var th=0,na=new Set,Ne=null;Aa(Ku);var Jf={RtcError:k,ErrorCode:V,ErrorCodeDictionary:Ct},jt=class extends ih.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",A.createLogger({id:`t${++th}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(N({logger:this._log,frameWorkType:jt.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(wi,t.assetsPath),this._use(or,t.assetsPath),t.enableSEI&&Gs&&this._use(Yr),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(M.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",s=>{this._log.error(new k({code:V.OPERATION_FAILED,extraCode:5504,message:s.message,originError:s}))}),this._listenEvents(),this._initActiveSpeaker(),zu(this,"trtc")}static create(e){}static _create(e,t){Bu();let s=new jt(e,t||{});return na.add(s),s}get room(){return this._room}_listenEvents(){ke(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=P(N({},e),{uplinkRTT:Math.min(e.uplinkRTT,fs),downlinkRTT:Math.min(e.downlinkRTT,fs)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{ke(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=uo(s.streamType)),this.emit(s.kind===h.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{_e(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,P(N({},e),{streamType:uo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new k({code:V.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,u,m;let t={2:"big",3:"small",7:"sub"},s={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,fs),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/dt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/dt},video:p.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(M.STATISTICS,s)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}),ke(this,Se).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ne&&Ne.deviceId===ps){let t=(yield Mi()).find(s=>s.deviceId===ps);t&&Ne.groupId!==t.groupId&&(Ne=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Mi())[0];t&&Ne&&(Ne.deviceId===e.deviceId||Ne.deviceId===ps&&Ne.groupId!==t.groupId)&&(Ne=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Qu.call(this,{TRTC:jt,room:this._room,errorModule:Jf,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,le(e.preferHW)&&(this._room.preferHW=e.preferHW);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};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,jt.frameWorkType),this._checkTrackToPublish(),Nd.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(){_e(this),this.removeAllListeners(),this._room.destroy(),na.delete(this),na.size===0&&Nd.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)})}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:s,option:o}=e,n=new Le(this._room.audioManager),a={},c={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(z(o.profile)?Po[o.profile]&&n.setProfile(Po[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.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",d=>{this.emit(M.ERROR,new k({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let u;d.error&&(u=k.convertFrom(d.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},d),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(s)||n.setMute(s),ke(n,n).add("player-state-changed",d=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(jt.EVENT.AUDIO_FRAME,{data:d})})),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):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(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ni(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),_e(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:s=!0,mute:o,option:n}=e,a=new he(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(n.profile)||(z(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),g(n.small)||(Fs()?z(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",u=>{this.emit(M.ERROR,new k({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let m;u.error&&(m=k.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},u),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let u=sr(n.qosPreference);a.mediaTrack.contentHint=u}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=sr(ot.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}ke(a,a).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,P(N({},u),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(g(n.profile)||(z(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&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?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=sr(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=c)}if(n.small){let c=!this._localVideoTrack.small;Fs()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:z(n.small)?this._localVideoTrack.small=Ze[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&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&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}),ni(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(),_e(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:s=!0,option:o}=e,n=new ze(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=k.convertFrom(m.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},m),{error:p}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(g(o.profile)||(z(o.profile)?xo[o.profile]&&n.setProfile(xo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),g(o.fillMode)||(d.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));let u=yield n.capture(c);if(o!=null&&o.qosPreference){let m=sr(o.qosPreference);n.mediaTrack.contentHint=m}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=sr(ot.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Gt(this._room.audioManager),a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),ke(n,n).add("player-state-changed",m=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,P(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[n];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=sr(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ni(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:t,playOption:d,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,B;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror));let u=null,m=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(u=m.remoteVideoTrack),o==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(u=m.remoteAuxiliaryTrack),!u)return;let{config:p}=c;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:u,prevConfig:p}),ni(p,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,C=g(t)?p.view:t,y=g(n==null?void 0:n.viewRoot)?(B=p.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:C,receiveWhenViewVisible:_,viewRoot:y})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!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}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return 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,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),e===jt.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(jt.EVENT.AUDIO_FRAME,{data:o})})),this)}emit(e,...t){try{qu.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(s){}return super.emit(e,...t)}off(e,t,s){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,s),e===jt.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,s=null,o="main",n=!1;if(z(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(s=a.remoteAudioTrack)}else s=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return s?n&&s.outMediaTrack&&s.outMediaTrack!==s.mediaTrack?s.outMediaTrack.clone():s.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main",processed:o=!1}=e,n=null;if(t==="")s==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),s==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=s==="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:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Mi()).forEach(s=>{s.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}),Ne=s)}),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,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(g(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),g(e)&&o&&o.view&&!Za(t)){let a=ws(o.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=ws(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){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 s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(M.TRACK,{userId:s,streamType:uo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${uo(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||fe(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.isIntersecting)}),clearTimeout(u),u=window.setTimeout(()=>{[...d.values()].find(C=>C)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(ws(t));d.forEach((p,_)=>{m.has(_)||(a.unobserve(_),d.delete(_))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),n.visibleViewMap=d,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",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{_e(e.remoteAudioTrack),_e(e.remoteVideoTrack),_e(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),_e(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(Ne&&!Vr(Ne))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ne});else{let e=yield Mi();if(e[0]&&!Vr(e[0]))Ne=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Ne||Vr(Ne))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_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 s=this._room.remotePublishedUserMap.get(e);if(s){let o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).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 s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),v.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){A.setLogLevel(e),g(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return _n()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Fe(e)}static getSpeakerList(e=!0){return Mi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Mi()).forEach(s=>{s.deviceId===e&&(na.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Ne=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(qi.version=a),e){case"count":qi.addCount({key:t,useUV:n});break;case"enum":qi.addEnum({key:t,value:s,useUV:n});break;case"number":qi.addNumber({key:t,value:s,split:o});break}}},X=jt;l(X,"_loggerManager",A),l(X,"EVENT",M),l(X,"ERROR_CODE",V),l(X,"TYPE",ot),l(X,"frameWorkType",30),b([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],X.prototype,"use",1),b([xe(Re.TRTC.enterRoom),Pi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),J(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],X.prototype,"enterRoom",1),b([ne()],X.prototype,"exitRoom",1),b([xe(Re.TRTC.switchRole),rr("room",{merge:(r,i)=>i}),ne()],X.prototype,"switchRole",1),b([ne()],X.prototype,"destroy",1),b([xe(Re.TRTC.startLocalAudio),Pi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ne()],X.prototype,"startLocalAudio",1),b([xe(Re.TRTC.updateLocalAudio),rr("audio",{debounce:{delay:200,getKey:()=>`${th}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],X.prototype,"updateLocalAudio",1),b([xi("audio"),ne()],X.prototype,"stopLocalAudio",1),b([xe(Re.TRTC.startLocalVideo),Pi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ne()],X.prototype,"startLocalVideo",1),b([xe(Re.TRTC.updateLocalVideo),rr("video"),ne()],X.prototype,"updateLocalVideo",1),b([xi("video"),ne()],X.prototype,"stopLocalVideo",1),b([xe(Re.TRTC.startScreenShare),Pi("screen",()=>!0),ne()],X.prototype,"startScreenShare",1),b([xe(Re.TRTC.updateScreenShare),rr("screen"),ne()],X.prototype,"updateScreenShare",1),b([ne()],X.prototype,"stopScreenShare",1),b([xe(Re.TRTC.startRemoteVideo),Pi(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"startRemoteVideo",1),b([xe(Re.TRTC.updateRemoteVideo),rr(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"updateRemoteVideo",1),b([xe(Re.TRTC.stopRemoteVideo),J(r=>function(i){return f(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"stopRemoteVideo",1),b([xi(r=>`v${r.userId}${r.streamType}`)],X.prototype,"_stopRemoteVideo",1),b([xe(...Re.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],X.prototype,"muteRemoteAudio",1),b([Cd(...Re.TRTC.setRemoteAudioVolume),Yu(200,r=>r),ne({getRemoteId:r=>r})],X.prototype,"setRemoteAudioVolume",1),b([ra("start"),It(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Pi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>dc[r.getName()]})],X.prototype,"startPlugin",1),b([ra("update"),rr((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>lc[r.getName()]})],X.prototype,"updatePlugin",1),b([ra("stop"),xi((r,i)=>{if(r.disableRandomCall)return null;let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>uc[r.getName()]})],X.prototype,"stopPlugin",1),b([Cd(...Re.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),b([ne()],X.prototype,"getVideoSnapshot",1),b([ne()],X.prototype,"_setCurrentSpeaker",1),b([Pi(r=>`a${r.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),b([J(r=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),xi(r=>`a${r.userId}`)],X.prototype,"_stopRemoteAudio",1),b([xi("room")],X.prototype,"_exitRoom",1),b([xi("screen")],X.prototype,"_stopScreenShare",1),b([xe(...Re.TRTC.sendSEIMessage),Sd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],X.prototype,"sendSEIMessage",1),b([xe(Re.TRTC.sendCustomMessage),Sd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],X.prototype,"sendCustomMessage",1),b([xe(Re.TRTC.create)],X,"_create",1);var ho=X;var wd=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function jf(){return f(this,null,function*(){let r,i;try{let m=yield Fe();r=m&&m.length}catch(m){}try{let m=yield Xe();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=wt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Y.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Y.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function rh(){return J(r=>{let i=new wd;return function(e,t,s){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 R({code:S.INVALID_OPERATION,message:x({key:L.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new R({code:S.INVALID_OPERATION,message:x({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(E.JOIN_START,{room:this,roomId:o,params:e});let n=Ve.getEnv();n||(n=zt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(wo.OLD_CLOUD_LADDER)?n=zt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(wo.WEBRTC)&&(n=zt.WEBRTC))),Y.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),wt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,jf.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ve.getEnv()&&(yield this.schedule(e,s));let a=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=Ve.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Y.uploadEvent({log:`stat-conv-${Number(ti)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(E.JOIN_FAILED,{room:this,error:a}),a}})}})}var sh=()=>J(r=>function(...i){return f(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function oh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var ah=Ie(Oe());var me={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var qt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},nh=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED],U={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var aa=new Set;function ch(r){let i=[...aa.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Kr=class extends ah.default{constructor(e){var s,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");l(this,"stopKeepAliveTimeout");l(this,"rtt",0);this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-aa.size>0&&this.room.enableSPC&&(this.keepAlive=!0,aa.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=A.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=w();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Ms(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?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(s?h.MAIN:h.BACKUP),c(new R({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===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse){if(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}this.room.isJoining&&this.emit(me.SETUP_FAILED,new R({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(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(me.SETUP_FAILED,new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=an(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(qt),c=Object.keys(qt)[n.indexOf(s)],d=U[c]||s;switch(nh.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&hl(o.svrTime),this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:w()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(me.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:x({key:L.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:u}),this.emit(me.SETUP_FAILED,u)}break}case qt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;kt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}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:s,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:U.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:w()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=an(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let u=setTimeout(()=>{this.off(o,p);let C=new R({code:S.API_CALL_TIMEOUT,message:x({key:L.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(C),d(C)},s),m=Date.now(),p=C=>{C.data.seq===_&&(clearTimeout(u),this.off(o,p),c(C),e===W.GET_USER_LIST&&(this.rtt=Date.now()-m))};this.on(o,p);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return Ot({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(me.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),aa.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(U.JOIN_ROOM_RESULT,t)},e*1e3);let t=s=>{s.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(U.JOIN_ROOM_RESULT,t))};this.on(U.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(me.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(me.CONNECTED):e==="DISCONNECTED"&&this.emit(me.DISCONNECTED))}};b([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],Kr.prototype,"connect",1);var dh=Ie(Oe());var Vd=0,Ud=!1,ca=new Set,Xf=r=>Vd>2&&!Ud&&ca.size===0&&r,Bd=!1,Ke=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new dh.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=A.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=w())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(w()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:w()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.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(),ca.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 R({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return at;let i=null;if(this._isUplink){if(!Di()||this._peerConnection.getSenders().length===0)return at;i=this._peerConnection.getSenders()[0].transport}else{if(!Xi()||this._peerConnection.getReceivers().length===0)return at;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:at}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===oe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===oe.FAILED||i.target.connectionState===oe.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new R({message:s,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===oe.CONNECTED||i.target.connectionState===oe.COMPLETED)&&(this.logSelectedCandidate(),Y.logSuccessEvent({userId:this._room.userId,eventType:Ue.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Vd=0,Ud=!1,Bd=!0,ca.add(this)):ca.delete(this),T.emit(E.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(vi(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new R({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Vd+=1,Xf(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Ud=!0,this._emitter.emit("firewall-restriction")),e(a)},ms);T.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(me.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Yt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new R({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:x({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(me.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var Gd=Ie(Hd());var de=function(r){return Gd.default.parse(r)},We=function(r){return Gd.default.write(r)},Eh=function(r){let i=de(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),We(i)};function gh(r){let i=de(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),We(i)}function da(r){return Object.keys(r).filter(i=>r[i])}var Jd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new mi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new At(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Jr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.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 Ni(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===hs?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
  61. `),s=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...s];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
  62. `)}addSPSDescription(e){let t=de(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),We(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=de(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),We(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===oe.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===oe.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 R({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){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=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${da(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=U.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=U.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new R({code:a.code,message:x({key:L.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}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:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:U.SUBSCRIBE_RESULT,timeout:Ma});if(!this._peerConnection){let a=new R({code:S.INVALID_OPERATION,message:x({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 f(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===Si?(this._peerConnection.addTransceiver(h.AUDIO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Q.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield fn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=gh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Eh(t.sdp),this._sdpSemantics===Si&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Fi)throw new R({code:S.NOT_SUPPORTED_H264,message:x({key:L.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new R({code:t,message:x({key:L.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{de(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(hs)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(hs)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ba)});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(!(Ae(Jd.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=Lt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}},fo=Jd;b([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],fo.prototype,"subscribe",1),b([It(Ke.prototype.afterConnect),On(Ke.prototype.beforeConnect)],fo.prototype,"connect",1);var Wd=fo;var Sh={voiceActivityDetection:!1},jd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(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});l(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,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Pt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(u[0].sender.track||m.push(0),yield u[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let p=o?3:1;yield u[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),m.push(p),s&&(yield u[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(Q.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){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),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}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(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Pt()){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=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(Q.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 f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:U.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:U.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:U.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?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Q.INACTIVE&&(yield this.setTransceiverDirection(Q.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Pt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.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===hr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=de(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;Pt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&te(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?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Q.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!re)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(d=>{n[d].direction!==e&&(n[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
  63. `).map(d=>{if(d.match(new RegExp(`a=(${Q.INACTIVE}|${Q.RECVONLY}|${Q.SENDONLY})`))&&a++,t.includes(a)){if(e===Q.INACTIVE&&d.includes(`a=${Q.RECVONLY}`))return o=!0,`a=${e}`;if(e===Q.SENDONLY&&d.includes(`a=${Q.INACTIVE}`))return o=!0,`a=${Q.RECVONLY}`}return d}).join(`\r
  64. `);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===h.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(s=>s.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===h.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(s=>{s.track&&s.track.kind===h.VIDEO&&this.removeSender(s)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return 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 s;if(tt()?s=e.kind===h.AUDIO?t[0]:t[1]:s=t.find(a=>a.track&&a.track.kind===e.kind),!s)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let s=yield this._peerConnection.createOffer(Sh);re&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_CHANGE,data:n,responseCommand:U.UPDATE_OFFER_RESULT,timeout:Oa,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),s.sdp&&this.updateSSRC(s.sdp)}catch(s){throw this._log.error(s),s}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:s,sdp:o}){if(!Hs())return o?t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e):void 0;let a,c=this._peerConnection.getSenders();if(tt()){let d=0;t===h.VIDEO&&(s===h.SMALL?d=2:s===h.AUXILIARY?d=3:d=1),a=c[d]}else a=c.find(d=>d.track&&d.track.kind===t);if(a){let d=a.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(d),this._log.info(`${s||""}${t} bandwidth ${e} kbps`),o}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),o)return t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,s){let o="AS";re&&(o="TIAS",t=t*1e3);let n=0,a=-1;return s===h.SMALL?n=1:s===h.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${o}:${t}\r
  65. `:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return re&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
  66. c=IN $2\r
  67. b=${s}:${t}\r
  68. `),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(Sh);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:W.PUBLISH,responseCommand:U.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ze||this.localAuxVideoTrack instanceof ze,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:o,data:n}=t.data;return s===0?this.acceptAnswer(n):this.checkPublishResultCode(s,o)})}setSDPDirection(e,t,s="all"){let o=de(e);return o.media.forEach(n=>{(s==="all"||n.type===s)&&(n.direction=t)}),We(o)}acceptAnswer(e){return f(this,null,function*(){var t,s,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),p=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let _=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:_})}p&&(c=yield this.setBandwidth({bandwidth:p,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:m}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||m.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(W.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(Ae(jd.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,responseCommand:U.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=Lt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{de(e).media.forEach((s,o)=>{if(s.type===h.AUDIO){let n=s.ssrcs&&s.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===hr&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let n=s.ssrcs&&s.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Fi?(this._log.error(Ce.NOT_SUPPORTED_H264ENCODE),new R({code:S.NOT_SUPPORTED_H264,message:x({key:L.NOT_SUPPORTED_H264ENCODE})})):new R({code:S.UNKNOWN,message:x({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:U.PUBLISH_RESULT,code:e,message:t}})})}},_o=jd;b([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],_o.prototype,"publish",1),b([It(Ke.prototype.afterConnect),On(Ke.prototype.beforeConnect)],_o.prototype,"connect",1);var Eo=_o;var go=class{constructor(i,e){this.room=i;l(this,"_log");l(this,"_prevReportTime",0);l(this,"_prevReport",{});l(this,"_prevStats",null);l(this,"_prevEncoderImplementation","");l(this,"_prevAuxEncoderImpl","");l(this,"_prevQualityLimitationReason","");l(this,"_prevAuxQualityLimitationReason","");l(this,"_prevDecoderImplementationMap",new Map);l(this,"totalBytesSent",0);l(this,"totalBytesReceived",0);l(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(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,m,p;let c,d;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===h.VIDEO){if(a.ssrc===s.video?(c=h.VIDEO,d=i.localMainVideoTrack):a.ssrc===s.small?c=h.SMALL:a.ssrc===s.auxiliary&&(d=i.localAuxVideoTrack,c=h.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,g(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),g(a.nackCount)||(e[c].nackCount=a.nackCount),g(a.pliCount)||(e[c].pliCount=a.pliCount),g(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),g(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),g(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!g(a.encoderImplementation)&&(c===h.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===h.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let C=2,y=this._prevEncoderImplementation;c===h.AUXILIARY&&(C=7,y=this._prevAuxEncoderImpl),T.emit("262",{userId:i.userId,streamType:C,prevImplementation:y,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===h.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===h.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===s.video?!g(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:(u=i.localMainVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===s.auxiliary&&!g(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:(m=i.localAuxVideoTrack)==null?void 0:m.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?vi(a)&&(this.totalBytesSent=a.bytesSent,ee(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===h.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===h.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!g(a.audioLevel)&&((p=i.localMainAudioTrack)==null?void 0:p.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!g(a.frameWidth)){let _=h.SMALL;a.trackIdentifier===i.getVideoTrackId(h.VIDEO)||a.ssrc===s.video?_=h.VIDEO:(a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||a.ssrc===s.auxiliary)&&(_=h.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===h.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===h.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===h.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 s;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:o}=i,{muteState:n,subscribeState:a}=i;(this._spcStats||(yield t.getStats())).forEach(d=>{if(d.type==="inbound-rtp"){let u=(d.mediaType||d.kind)===h.AUDIO;if(u){if(d.ssrc!==o.audio||!n.hasAudio)return;e.audio.packetsReceived=d.packetsReceived,e.audio.bytesReceived=d.bytesReceived,e.audio.packetsLost=d.packetsLost,d.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=d.insertedSamplesForDeceleration),d.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=d.removedSamplesForAcceleration),d.totalSamplesDuration&&(e.audio.totalSamplesDuration=d.totalSamplesDuration),d.totalSamplesReceived&&(e.audio.totalSamplesReceived=d.totalSamplesReceived),d.concealedSamples&&(e.audio.concealedSamples=d.concealedSamples);let{remoteAudioTrack:m}=i;m.stat.packetsReceived=d.packetsReceived,m.stat.bytesReceived=d.bytesReceived,m.stat.packetsLost=d.packetsLost,e.audio.p2pDelay=m.stat.end2EndDelay,e.hasAudio=!0}else{if(re&&d.bytesReceived===0)return;let m;d.ssrc===o.video&&n.hasVideo&&(e.video.packetsReceived=d.packetsReceived,e.video.bytesReceived=d.bytesReceived,e.video.packetsLost=d.packetsLost,e.video.framesReceived=d.framesReceived,e.video.framesDecoded=d.framesDecoded,e.video.fpsDecoded=d.framesPerSecond,e.hasVideo=!0,m=i.remoteVideoTrack,n.hasSmall&&a.smallVideo&&(e.isSmallSubscribed=!0),d.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==d.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${d.decoderImplementation} HWDecoder: ${d.powerEfficientDecoder}`),T.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:d.decoderImplementation,codec:i.videoCodec,isHWCodec:d.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,d.decoderImplementation))),d.ssrc===o.auxiliary&&n.hasAuxiliary&&(e.auxiliary.packetsReceived=d.packetsReceived,e.auxiliary.bytesReceived=d.bytesReceived,e.auxiliary.packetsLost=d.packetsLost,e.auxiliary.framesReceived=d.framesReceived,e.auxiliary.framesDecoded=d.framesDecoded,e.auxiliary.fpsDecoded=d.framesPerSecond,m=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),m&&(m.stat.packetsReceived=d.packetsReceived,m.stat.bytesReceived=d.bytesReceived,m.stat.packetsLost=d.packetsLost,m.stat.framesReceived=d.framesReceived,m.stat.framesDecoded=d.framesDecoded,d.jitterBufferDelay&&(m.stat.jitterBufferDelay=Math.floor(d.jitterBufferDelay/d.jitterBufferEmittedCount*1e3)))}d.jitterBufferDelay&&(u?(e.audio.totalJitter=d.jitterBufferDelay,e.audio.totalJitterCount=d.jitterBufferEmittedCount):d.ssrc===o.video&&n.hasVideo?(e.video.totalJitter=d.jitterBufferDelay,e.video.totalJitterCount=d.jitterBufferEmittedCount):d.ssrc===o.auxiliary&&n.hasAuxiliary&&(e.auxiliary.totalJitter=d.jitterBufferDelay,e.auxiliary.totalJitterCount=d.jitterBufferEmittedCount))}else d.type==="candidate-pair"&&vi(d)&&(this.totalBytesReceived=d.bytesReceived,ee(d.currentRoundTripTime)&&(e.rtt=Math.floor(d.currentRoundTripTime*1e3)));g(d.frameWidth)||((d.trackIdentifier===i.getMainStreamVideoTrackId()||d.ssrc===o.video)&&(e.video.frameWidth=d.frameWidth,e.video.frameHeight=d.frameHeight,i.remoteVideoTrack.stat.frameWidth=d.frameWidth,i.remoteVideoTrack.stat.frameHeight=d.frameHeight),(d.trackIdentifier===i.getAuxStreamVideoTrackId()||d.ssrc===o.auxiliary)&&(e.auxiliary.frameWidth=d.frameWidth,e.auxiliary.frameHeight=d.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=d.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=d.frameHeight)),!g(d.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&d.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=d.audioLevel||0,e.audio.totalAudioEnergy=d.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(o){this._log.warn(`failed to getStats on receiver connection ${o}`)}return e.rtt===0&&(e.rtt=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},s=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:s};let n=w(),a=yield o.getStats(),c=w();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let d=[],u=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(m=>u.has(m.type)&&d.push(m)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Ft(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m;if(!Ft(i.senderStats)){let p={uint32_audio_level:i.senderStats.audio.audioLevel*dt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(p.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let _=[];if(i.senderStats.video.bytesSent){let y={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(y)}if(i.senderStats.small.bytesSent){let y={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(y)}if(i.senderStats.auxiliary.bytesSent){let y={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(y)}let C={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:p,msg_video_status:_,msg_network_status:C}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(p=>{let _={msg_user_info:{str_identifier:p.userId,uint64_tinyid:p.tinyId},msg_network_status:{uint32_rtt:p.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(p.hasAudio){let C={uint32_audio_p2p_delay:p.audio.p2pDelay,uint32_audio_cache_ms:p.audio.totalJitter,uint32_audio_cache_ms_count:p.audio.totalJitterCount,uint32_audio_codec_bitrate:p.audio.bytesReceived,uint32_audio_total_bitrate:p.audio.bytesReceived,uint32_audio_level:p.audio.audioLevel*1e8,uint32_audio_energy:p.audio.totalAudioEnergy*1e6,uint32_audio_receive:p.audio.packetsReceived,uint32_audio_origin_lost:p.audio.packetsLost};_.msg_audio_status=C}if(p.hasVideo){let C=t.get(`${p.userId}_${Na}`),y=C?C.duration:0,D={uint32_video_stream_type:p.isSmallSubscribed?3:2,uint32_video_receive_fps:p.video.framesReceived,uint32_video_width:p.video.frameWidth,uint32_video_height:p.video.frameHeight,uint32_video_codec_bitrate:p.video.bytesReceived,uint32_video_receive:p.video.packetsReceived,uint32_video_origin_lost:p.video.packetsLost,uint32_video_block_time:y,uint32_video_dec_fps:p.video.framesDecoded,uint32_video_cache_ms:p.video.totalJitter,uint32_video_cache_ms_count:p.video.totalJitterCount};_.msg_video_status.push(D)}if(p.hasAuxiliary){let C=t.get(`${p.userId}_${va}`),y=C?C.duration:0,D={uint32_video_stream_type:7,uint32_video_receive_fps:p.auxiliary.framesReceived,uint32_video_width:p.auxiliary.frameWidth,uint32_video_height:p.auxiliary.frameHeight,uint32_video_codec_bitrate:p.auxiliary.bytesReceived,uint32_video_receive:p.auxiliary.packetsReceived+p.auxiliary.packetsLost,uint32_video_origin_lost:p.auxiliary.packetsLost,uint32_video_block_time:y,uint32_video_dec_fps:p.auxiliary.framesDecoded,uint32_video_cache_ms:p.auxiliary.totalJitter,uint32_video_cache_ms_count:p.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 p=o.msg_up_stream_info.msg_audio_status,_=e.msg_up_stream_info.msg_audio_status;if(p.uint32_audio_codec_bitrate===0)_.uint32_audio_codec_bitrate=0;else{let C=this.getDifferenceValue(p.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(C*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_audio_codec_bitrate}(m=o.msg_device_info)!=null&&m.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/s):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(p=>{let _=a.find(ve=>ve.uint32_video_stream_type===p.uint32_video_stream_type);if(!_||_.uint32_video_codec_bitrate===0){p.uint32_video_codec_bitrate=0,p.uint32_video_enc_fps=0,p.uint32_video_codec_fps=0;return}let C=0,y=0,D=0;_&&p.uint32_video_codec_bitrate>=_.uint32_video_codec_bitrate&&(C=_.uint32_video_codec_bitrate,y=_.uint32_video_enc_fps,D=_.uint32_video_codec_fps);let B=this.getDifferenceValue(C,p.uint32_video_codec_bitrate);p.uint32_video_codec_bitrate=Math.round(B*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=p.uint32_video_codec_bitrate,p.uint32_video_enc_fps=Math.round(this.getDifferenceValue(y,p.uint32_video_enc_fps)/s),p.uint32_video_codec_fps=Math.round(this.getDifferenceValue(D,p.uint32_video_codec_fps)/s),Zt&&ei()===115&&_.uint32_video_width===0&&_.uint32_video_height===0&&_.uint32_video_codec_fps===0&&(p.uint32_video_codec_fps=p.uint32_video_enc_fps),g(_.uint32_key_frame_count)||(p.uint32_key_frame_count=Math.round(this.getDifferenceValue(_.uint32_key_frame_count,p.uint32_key_frame_count))),g(_.uint32_nack_count)||(p.uint32_nack_count=Math.round(this.getDifferenceValue(_.uint32_nack_count,p.uint32_nack_count))),g(_.uint32_pli_count)||(p.uint32_pli_count=Math.round(this.getDifferenceValue(_.uint32_pli_count,p.uint32_pli_count))),g(_.uint32_video_arq_packets)||(p.uint32_video_arq_packets=Math.round(this.getDifferenceValue(_.uint32_video_arq_packets,p.uint32_video_arq_packets))),g(_.uint32_encode_cost)||(p.uint32_encode_cost=Math.round(this.getDifferenceValue(_.uint32_encode_cost,p.uint32_encode_cost)/s)),g(_.uint32_send_packet_cost)||(p.uint32_send_packet_cost=Math.round(this.getDifferenceValue(_.uint32_send_packet_cost,p.uint32_send_packet_cost)/s))});let d=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(p=>d.find(_=>_.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid));let u=e.msg_down_stream_info;return u.forEach(p=>{let _=d.find(C=>C.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid);if(!Ft(p.msg_audio_status)&&!Ft(_.msg_audio_status)){let C=p.msg_audio_status,y=_.msg_audio_status,D=this.getDifferenceValue(y.uint32_audio_cache_ms_count,C.uint32_audio_cache_ms_count);delete C.uint32_audio_cache_ms_count,C.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(y.uint32_audio_cache_ms,C.uint32_audio_cache_ms)/D)||0;let B=this.room.remotePublishedUserMap.get(p.msg_user_info.str_identifier);B&&(B.remoteAudioTrack.stat.jitterBufferDelay=C.uint32_audio_cache_ms),C.uint32_audio_origin_lost=this.getDifferenceValue(y.uint32_audio_origin_lost,C.uint32_audio_origin_lost),C.uint32_audio_receive=this.getDifferenceValue(y.uint32_audio_receive,C.uint32_audio_receive),C.uint32_audio_receive+=C.uint32_audio_origin_lost;let ve=this.getDifferenceValue(y.uint32_audio_codec_bitrate,C.uint32_audio_codec_bitrate);C.uint32_audio_codec_bitrate=Math.round(ve*8/s),C.uint32_audio_total_bitrate=Math.round(ve*8/s)}else p.msg_audio_status={};if(p.msg_video_status&&_.msg_video_status){let C=_.msg_video_status;p.msg_video_status=p.msg_video_status.filter(D=>C.find(B=>B.uint32_video_stream_type===D.uint32_video_stream_type)),p.msg_video_status.forEach(D=>{let B=C.find(im=>im.uint32_video_stream_type===D.uint32_video_stream_type),ve=B.uint32_video_receive,vo=B.uint32_video_origin_lost,Yh=B.uint32_video_codec_bitrate,G=B.uint32_video_receive_fps,Kh=B.uint32_video_dec_fps;D.uint32_video_origin_lost=this.getDifferenceValue(vo,D.uint32_video_origin_lost),D.uint32_video_receive=this.getDifferenceValue(ve,D.uint32_video_receive)+D.uint32_video_origin_lost;let Zh=this.getDifferenceValue(Yh,D.uint32_video_codec_bitrate);D.uint32_video_codec_bitrate=Math.round(Zh*8/s);let em=this.getDifferenceValue(G,D.uint32_video_receive_fps);D.uint32_video_receive_fps=Math.round(em/s),D.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Kh,D.uint32_video_dec_fps)/s);let tm=this.getDifferenceValue(B.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(B.uint32_video_cache_ms,D.uint32_video_cache_ms)/tm)||0})}}),n&&i.receiverStats.forEach(p=>{if(p.audio.concealedSamples&&p.audio.totalSamplesReceived){let _=n.receiverStats.find(C=>C.userId===p.userId);if(_&&_.audio.concealedSamples&&_.audio.totalSamplesReceived){let C=p.audio.concealedSamples-_.audio.concealedSamples,y=p.audio.totalSamplesReceived-_.audio.totalSamplesReceived,D=Math.floor(C/y*1e3*s);if(D>s/5){let B=u.find(ve=>ve.msg_user_info.str_identifier===p.userId);B&&(B.msg_audio_status.uint32_audio_block_time=D)}}}}),e}getStatsReport(s){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 Ch=Ie(Oe());function Ih(r){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===r){let s=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),d=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),m=Math.round(t.responseStart-t.requestStart),p=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=P(N({},i),{totalCost:s,local:o,redirect:n,httpCache:a,dns:c,tcp:u,tls:d,request:m,response:p});break}}catch(e){}return i}function Ah(r){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(),s=`https://${r}/?t=${t}`;try{yield fetch(s)}catch(n){}clearTimeout(e);let o=Ih(s);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var s_=700,To=class extends Ch.default{constructor({signalChannel:e,room:t}){super();l(this,"_room");l(this,"_signalChannel");l(this,"_log");l(this,"uplinkRTT",0);l(this,"uplinkLoss",0);l(this,"downlinkRTT",0);l(this,"downlinkLoss",0);l(this,"pingResults",{});l(this,"_downlinkPrevStatMap",new Map);l(this,"_downlinkLossAndRTTMap",new Map);l(this,"_interval",-1);l(this,"_uplinkNetworkQuality",0);l(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=A.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(U.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(me.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let s=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let 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 c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===oe.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:u,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:m});continue}let p=0,_=this._downlinkPrevStatMap.get(c),C=u-_.totalPacketsLost,y=m-_.totalPacketsReceived;C<=0||y<0?p=0:p=Math.round(C/(C+y)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:p,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Xi())return t;let s=e.getReceivers();try{for(let o=0;o<s.length;o++)(yield s[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&ee(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===h.AUDIO||c.mediaType===h.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.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(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===oe.DISCONNECTED||e.connectionState===oe.FAILED||e.connectionState===oe.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=Z.run(Ii,()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(E.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,s={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(s=P(N({},s),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(To.EVENT_NETWORK_QUALITY,s);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-To.lastPingTime>t.interval*1e3){To.lastPingTime=Date.now();let a=t.domain.map(c=>Ah(c).then(d=>({domain:c,cost:d.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(d=>d.cost>s_),this.pingResults.timestamp=o,this.pingResults.data=c,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&&(Z.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:o,audioDelay:n})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}},Ui=To;l(Ui,"EVENT_NETWORK_QUALITY","0"),l(Ui,"lastPingTime",0);function o_({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return Ls(t)?t.catch(s=>A.error(`${r.name}() error observed ${s}`)):t}catch(t){A.error(`${r.name}() error observed ${t}`)}}}var la=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._captureCostSum=0;this._captureCostCount=0;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=A.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&te(this[e])&&(this[e]=o_({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:ye,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,vs().then(i=>{this._basicInfo.string_os_version=ri(),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(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!gt(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>T.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Z.clearTask(this._intervalId),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:s,dns:o,tcp:n,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof R?Number(e.getExtraCode()||e.getCode()):S.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let 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:P(N({},n_),{msg_user_info:new So({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new So({userId:o,tinyId:n,role:a==="anchor"?20:21}),d=Date.now(),u=`${o}_${t}`,m=this._remoteStreamStatMap.get(u);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=d),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{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:d}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(s);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!gt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!gt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),o)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let n=this._pathAuxiliaryMap.get(e);if(n&&o){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-n.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,u,m;o&&(d=o,u=1),n&&(c=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:m,videoDelayCount:u})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:s}=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/dt*100)>0&&(this._localStreamStat.totalAudioLevel+=o/dt,this._localStreamStat.audioLevelCount++)}s.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,d=n.str_identifier,u=this._room.remotePublishedUserMap.get(d);if(c.forEach(m=>{let p=m.uint32_video_stream_type===2,_=m.uint32_video_stream_type===7,C=`${d}_${p?"main":"auxiliary"}`,y=this._remoteStreamStatMap.get(C);if(!!y&&(p&&(u==null?void 0:u.remoteVideoTrack.isSubscribed)||_&&(u==null?void 0:u.remoteAuxiliaryTrack))){y.totalVideoFPS+=m.uint32_video_receive_fps,y.totalVideoBitrate+=m.uint32_video_codec_bitrate,y.videoCount++,y.statsToReport.uint32_video_width===0&&(y.statsToReport.uint32_video_width=m.uint32_video_width),y.statsToReport.uint32_video_height===0&&(y.statsToReport.uint32_video_height=m.uint32_video_height);let D=p?u.remoteVideoTrack:u.remoteAuxiliaryTrack;D.stat.jitterBufferDelay&&(y.videoJitterBufferDelay=D.stat.jitterBufferDelay),D.stat.framesReceived&&(y.statsToReport.uint32_video_consume_render_rate=Math.floor(D.stat.framesDecoded/D.stat.framesReceived*ss(10,6)))}}),a){let m=`${d}_${"main"}`,p=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&p&&(u==null?void 0:u.remoteAudioTrack.isSubscribed)&&(p.totalAudioBitrate+=a.uint32_audio_codec_bitrate,p.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(p.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/dt*100)>0&&(p.totalAudioLevel+=a.uint32_audio_level/dt,p.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 s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof R?e.getExtraCode()||e.getCode():S.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&gi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Ti)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&$i)>=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,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:u,count:m,audioDelayCount:p,videoDelayCount:_,totalAudioDelay:C,totalVideoDelay:y}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(u/m),p&&C&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(C/p),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&y&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/_))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,ar);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:d}=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(d,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>ar&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+ar)}),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>ar&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+ar)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>ar&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+ar)}getReportData(){this._basicInfo.uint32_networkType=Or();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new So({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:xs(this._signalInfo.relayIp),uint32_client_ip:xs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*ss(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:xs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return cn(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 xa(i),s=t instanceof ArrayBuffer,o=`${yi(e,Ei.KEY_POINT)}&gzip=${+s}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(v),this.uploadKVStat(qi)];n||a.push(Kt({url:o,body:t})),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=P(N({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield xa(e),s=`${yi(+this._room.sdkAppId,Ei.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(s,t)),o||Kt({url:s,body:t})})}};b([it({settings:{timeout:500,retries:3}})],la.prototype,"upload",1);var ar=5e3,n_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},So=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Rh=la;var qd=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=w())}stop(){this._endTime===0&&(this._endTime=w())}getDuration(){return this._endTime===0?w()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},es=qd;var Xd=class{constructor(i){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(E.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,h.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!o||(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let n=new es,a=this._durationMap.get(o);a?this.isRecording(a.audio)||a.audio.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[n],video:[]})}else this.stopDurationItem(o,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let n=new es,a=this._durationMap.get(o);a?this.isRecording(a.video)||a.video.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[],video:[n]})}else this.stopDurationItem(o,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,o=new es,n=this._durationMap.get(s);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(o=>o.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,o)=>s+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},yh=Xd;var Qd=class{constructor(i){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDataFreeze({key:o,userId:s,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!gt(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,o=this._dataFreezeMap.get(s),n=new es;o?o.durationItemList.push(n):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:o,muteState:n}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let o=s.durationItemList[s.durationItemList.length-1];o.stop();let n=o.getDuration();n>Bo?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return f(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=w();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=w();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!gt(i)||!this.hitTest(i.room)||i.kind!==h.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<Bo&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=w(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},bh=Qd;var Nh=Ie(Oe(),1);var a_=[1,0,0,0,1,1,0,1],ua=class extends Ye{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof be)try{this.setTexBuffer(a_)}catch(t){i.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,s,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,s,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 zd=class{constructor(i,e){this.node=i;this.layout=e;l(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},ha=class extends Ye{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});l(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let s=new zd(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(s.width,s.height),this.context instanceof be&&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((s,o)=>(!o||!o.node.requestFrame(e))&&s,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:o,height:n,name:a}=this,c=Date.now(),d=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:c,fps:d,name:a},N({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,s;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof be))try{(s=this.context.ctx)==null||s.deleteBuffer(e.positionBuffer)}catch(o){}})}};var c_=`#version 300 es
  69. in vec2 a_position;
  70. in vec2 a_texCoord;
  71. out vec2 v_texCoord;
  72. void main() {
  73. gl_Position = vec4(a_position.x, a_position.y, 0, 1);
  74. v_texCoord = a_texCoord;
  75. }`,d_=`#version 300 es
  76. precision highp float;
  77. uniform sampler2D u_texture;
  78. uniform sampler2D mask;
  79. in vec2 v_texCoord;
  80. out vec4 outColor;
  81. void main() {
  82. outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
  83. }`,ma=class extends Wr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});l(this,"_bgTexture");l(this,"_waterMarkTexture");l(this,"_lastMaskTexture");l(this,"_lastMaskFbo");l(this,"_textureValid",!1);l(this,"_selfieTextureValid",!1);l(this,"_selfieSegmentation");l(this,"wasm");l(this,"_prePrograme");l(this,"_segmentationMask");l(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(s){e.log.error(s),e.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${s.message||s}`}))}}init(e){var o,n;let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:a,y:c,width:d,height:u}=e.waterMark;this.wasm.setWaterMark(a,c,d,u)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:d}=e.beautyParams;this.wasm.setBeauty(a,c,d,(o=this.context._canvas)==null?void 0:o.width,(n=this.context._canvas)==null?void 0:n.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(s.FRAGMENT_SHADER,d_),c=this.context.createShader(s.VERTEX_SHADER,c_);this._prePrograme=this.context.createProgram(c,a),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var s;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),(s=this._selfieSegmentation)==null||s.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var c,d,u,m;let t=this.context.ctx,{image:s}=this;Qi()&&s.requestVideoFrameCallback((p,_)=>{this._totalFrames=_.presentedFrames,this.update()});let{videoWidth:o,videoHeight:n}=s;s.width=o,s.height=n;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():(c=this._selfieSegmentation)==null||c.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,s)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,s),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(d=this._selfieSegmentation)==null||d.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)),(m=this._selfieSegmentation)==null||m.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 pa=class extends Nh.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"cameraTrack");l(this,"cameraNode");l(this,"mirrorNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",A.createLogger({id:"vm"}));l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"_selfieSegmentation");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new 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 be({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update()})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=Z.run(Gi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(yr||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:s,error:t}):v.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new be({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let s=this.cameraTrack,{small:o,settings:n,player:a}=s;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Xn(this.smallVideoContext,o,this.log)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),yr&&a.setCanvas(e);let c=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${c?c.label:"no output track"}`),s.setOutputMediaStreamTrack(c)}catch(s){this.log.error("set main output failed",s)}}update(){return f(this,null,function*(){var s,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new qn(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new ma(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new ua(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new ha(this.videoContext,this.log),n.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),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,o,n;if(e instanceof ze)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",(s=e.mediaTrack)==null?void 0:s.label),this.setCameraTrack(e);if(e instanceof At){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)}configPipeline(e){e instanceof At}removeInput(e){var t;e instanceof ze?((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 At&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return f(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let o=s.getContext("2d");if(!o)throw new R({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:d,height:u})=>{o.drawImage(n,a,c,d,u)}),Vs(s.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*(){let t;try{t=yield Vs((e==null?void 0:e.imageElement)||e.imageUrl)}catch(u){throw new R({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:o,width:n,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var t,s,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(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 Vs(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 R({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()}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}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};var l_=0;var fa=class extends F{constructor(e){super("room");this.seq=++l_;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}};this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=A.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,le(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),le(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),le(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Rh({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new yh({room:this}),this.badCaseDetector=new bh({room:this}),this.audioManager=new xn(this),this.videoManager=new pa(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(z(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Je(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Ya([a,a]),Bi(`https://${a}`)):(o&&Bi(o),n&&Ya(n))}T.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:bi.main,sched_back_domain:bi.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 s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new R({code:S.INVALID_OPERATION,message:x({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ce.INVALID_DESTROY),new R({code:S.INVALID_OPERATION,message:x({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(E.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var o,n;let s=w();try{let{isCached:a,result:c,detailCost:d}=yield vl({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ye,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${Et(c,{keysToExclude:["username","credential"]})}`),a&&T.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),ee((o=c.config)==null?void 0:o.retryCount)&&Da(c.config.retryCount),z((n=c.config)==null?void 0:n.loggerDomain)&&Bi(c.config.loggerDomain),T.emit(E.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),v.addSuccessEvent({key:521700,cost:w()-s,split:50})}catch(a){throw v.addFailedEvent({key:521700,error:a}),a}})}};var Dh=Ie(Oe(),1);var vh=Symbol("instance"),cP=Symbol("abortCtrl"),Yd=Symbol("cacheResult"),Io=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Ro.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Ao=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function u_(r){return typeof r=="object"&&r&&"then"in r}var Co=new Map;function Kd(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=Co.get(t)||[];Co.has(t)||Co.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=ae.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[Yd];d.state instanceof Io&&d.state.action==e.abortAction&&d.state.abort(d);let u=null;if(Array.isArray(r)?r.length==0?d.state instanceof Io&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(u=new Ao(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(u=new Ao(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let m=d.state,p=new Io(m,i,n);Ro.call(d,p);let _=y=>{var D;return d[Yd]=y,p.aborted||(Ro.call(d,i),(D=e.success)===null||D===void 0||D.call(this,d[Yd])),y},C=y=>{let D=y instanceof Error?y.message:String(y);if(Ro.call(d,m,y),e.fail)e.fail.call(this,new Ao(d._state,`action '${n}' failed :${D}`,y instanceof Error?y:new Error(D)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return u_(y)?y.then(_).catch(C):_(y)}catch(y){C(y)}}}}var h_=(()=>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 Ro(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(ae.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var ae=class extends Dh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ae.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[vh];s?this.name=s.name+"-"+s.count++:t[vh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Co.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Co.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:u,action:m})=>{typeof d=="string"?s.push({from:d,to:u,action:m}):d.length?d.forEach(p=>{s.push({from:p,to:u,action:m})}):o.push({to:u,action:m})}),s.forEach(({from:d,to:u,action:m})=>{n.add(d),n.add(u),n.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${u} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),o.forEach(({to:d,action:u})=>{t.add(`${u}ing --> ${d} : ${u} \u{1F7E2}`),n.forEach(m=>{m!==d&&t.add(`${m} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=ae.instances.get(i),e||ae.instances.set(i,e=new ae(i,void 0,Object.create(ae.prototype)))):(e=ae.instances2.get(i),e||ae.instances2.set(i,e=new ae(i.constructor.name,void 0,Object.create(ae.prototype)))),e}static getState(i){var e;return(e=ae.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){h_(ae.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Ro.call(this,i)}};ae.STATECHANGED="stateChanged";ae.UPDATEAFSM="updateAFSM";ae.INIT="[*]";ae.ON="on";ae.OFF="off";ae.instances=new Map;ae.instances2=new WeakMap;var Fh=Ie(Oe());var Zd=Ie(Hd());var Oh=r=>{let i=de(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var o;if(t.ssrcs&&!g(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(s){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function Mh(r){var e;let i=[];for(let t=0;t<r.rtp.length;t++){if(["rtx","red","ulpfec"].includes(r.rtp[t].codec))continue;let s=r.fmtp.filter(o=>o.payload===r.rtp[t].payload)[0];i.push({payload:r.rtp[t].payload,codec:r.rtp[t].codec,fmtp:s?s.config:"",rate:r.rtp[t].rate,rtx:((e=r.rtp[t+1])==null?void 0:e.codec)==="rtx"?r.rtp[t+1].payload:0,rtcpFb:((r==null?void 0:r.rtcpFb)||[]).filter(o=>o.payload===r.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function m_(){return f(this,null,function*(){let r=new RTCPeerConnection;r.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield r.createOffer();if(!i.sdp)return[];let e=de(i.sdp),t=Mh(e.media[0]);return r.close(),t})}var kh=(r,i)=>f(void 0,null,function*(){var c;let e=de(r),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 s=e.media[0],o=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),o.ext&&(t.video.extensions=o.ext.map(d=>({id:d.value,uri:d.uri})));let n={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(c=s.rtcpFb)==null||c.forEach(({payload:d,type:u,subtype:m})=>{if(d===n.payload){let p={id:u,params:[]};m&&p.params.push(m),n.rtcpFb.push(p)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...Mh(o)].filter(d=>a.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield m_()).filter(d=>["h264","vp8"].includes(d.codec.toLocaleLowerCase())),t}),Lh=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=de(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(el({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&o.media.push(s.media.find(a=>a.mid==="dc")),We(o)},el=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:s=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s)(i.video.decoders||i.video.codecs).forEach(n=>{cr(o,n)});else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];cr(o,a)}return o},cr=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`.trim(),r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function p_(r){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);r.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function f_(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function __(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function E_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Ph=(r,i,e)=>{let t=Zd.default.parse(r);return t.media.forEach((s,o)=>{var n;(s.type===h.AUDIO||s.type===h.VIDEO)&&(f_(s),__(s),E_(s),p_(s),s.type===h.VIDEO&&(o<4?(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],i.video.codecs.forEach(a=>cr(s,a))):e&&(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],(e.video.decoders||e.video.codecs).forEach(a=>cr(s,a))))),((n=s.payloads)==null?void 0:n.includes("datachannel"))&&t.groups&&s.mid&&(t.groups[0].mids=t.groups[0].mids.replace(s.mid,"dc"),s.mid="dc")}),Zd.default.write(t)};var xh=Ie(Oe());var _a=class extends xh.EventEmitter{constructor(e){super();this.room=e;l(this,"mainFpsHealth",1);l(this,"mainBitrateHealth",1);l(this,"badMainBitrateHealthCount",0);l(this,"lastEmitBadHealthTime",0);l(this,"log");!pe&&pt&&T.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:s,codec:o}){if(!(e||t===7||o!=="h264")){if(!s){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 s=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=s)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:s}=this.room;s&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/s.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)}};l(_a,"EVENT_BAD_HEALTH","bad_health");var wh=_a;function Vh({seiMessageList:r,isAudio:i}){return new TransformStream({transform(e,t){let s=e;i?audioEncodePipeline.forEach(o=>{s=o({frame:s})}):videoEncodePipeline.forEach(o=>{s=o({frame:s,seiMessageList:r})}),t.enqueue(s)}})}function Uh(r,i){return new TransformStream({transform(e,t){let s=e;videoDecodePipeline.forEach(o=>{s=o({frame:s,onSEI:n=>{n.forEach(a=>{self.postMessage({type:"sei",seiPayloadType:a.seiPayloadType,data:a.seiPayload.buffer,userId:r,streamType:i})})}})}),t.enqueue(s)}})}function Bh(r){let i=[hi],e=[Md,Dd,Od,vd,Vh,Uh],t=()=>{let d=[],u=[],m=[];self.onmessage=p=>{p.data.type==="sei"&&(p.data.isMain?(d.push(p.data.data),p.data.small&&m.push(p.data.data)):u.push(p.data.data))},self.onrtctransform=p=>{let{options:_}=p.transformer,C=_.isReceiver?Uh(_.userId,_.streamType):Vh({seiMessageList:_.isMain?_.small?m:d:u});p.transformer.readable.pipeThrough(C).pipeTo(p.transformer.writable)}},s=`const videoEncodePipeline=[${r.videoEncodePipeline.toString()}];
  84. const videoDecodePipeline=[${r.videoDecodePipeline.toString()}];
  85. const audioEncodePipeline = [${r.audioEncodePipeline.toString()}];
  86. const audioDecodePipeline = [${r.audioDecodePipeline.toString()}];`,o=`(()=>{${i.map(d=>`const ${d.name}=(()=>${d.toString()})()`).join(`
  87. `)}
  88. ${e.map(d=>d.toString()).join(`
  89. `)};(${t})();${s}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var Xt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(Xt||{}),Hh=0,Gh=!1,g_=new Set,T_=r=>Hh>2&&!Gh&&g_.size===0&&r,S_=1,_i=class extends Fh.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();l(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});l(this,"currentState","DISCONNECTED");l(this,"_room");l(this,"_signalChannel");l(this,"_peerConnection",null);l(this,"_datachannel",null);l(this,"_enableCustomMessage");l(this,"_log");l(this,"_downlinkMIDMap",new Map);l(this,"_downlinkMIDUserIDMap",new Map);l(this,"_reconnectionTimer",-1);l(this,"reconnectionCount",0);l(this,"clientAbility");l(this,"_serverAbility",null);l(this,"addDownlinkQueue",new Set);l(this,"removeDownlinkQueue",new Set);l(this,"_parsedAnswer",null);l(this,"_updateSDPPromise",null);l(this,"_waitForPCConnectedPromise");l(this,"_isSDPLogged",!1);l(this,"enableInsertableStreams",!1);l(this,"insertableStreamsAbortMap",new Map);l(this,"scriptTransformWorker");this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${S_++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Tt?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 s;(s=this.insertableStreamsAbortMap.get(e))==null||s.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,s;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():(s=this._serverAbility)!=null&&s.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?Oh(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(){En&&(this.scriptTransformWorker=Bh({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)},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}initialize(){return f(this,null,function*(){var t;let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),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=s=>{let o=new il(s.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield kh(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;!s||(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),v.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw v.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
  90. offer: ${e==null?void 0:e.sdp}`),s}})}setPriority(e="high"){if(!!this._peerConnection)try{this._peerConnection.getSenders().forEach(s=>{let o=s.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,s.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 s,o;try{if(this.currentState==="CONNECTED")return;let n=w(),a={type:"answer",sdp:Lh({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(a),yield this.waitForPeerConnectionConnected();let c=((s=this._room.scheduleResult.config)==null?void 0:s.priority)||((o=this._room.joinParams)==null?void 0:o.priority)||new URLSearchParams(location.search).get("priority");c&&this.setPriority(c),t||v.addSuccessEvent({key:521703,cost:w()-n})}catch(n){let a=n instanceof R&&n.code===S.API_CALL_ABORTED;throw a||this._log.error(`connect failed: ${n}`,e),this.reset(),!a&&!this.isReconnecting&&(v.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}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(me.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:U.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new R({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(E.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Lt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),v.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Yt()&&this._log.warn(`SDK has tried reconnect for ${Yt()} 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._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(me.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===oe.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===oe.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===oe.FAILED||e.target.connectionState===oe.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===oe.CONNECTED||e.target.connectionState===oe.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(E.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 at;let e=null;return!Di()||this._peerConnection.getSenders().length===0?at:(e=this._peerConnection.getSenders()[0].transport,!Xi()||this._peerConnection.getReceivers().length===0?at:e?e.state:at)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Xt.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,s]of e)if(vi(s)){let o=e.get(s.localCandidateId),n=e.get(s.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Ka(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 s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,o,this),this.off(Xt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{n();let c=new R({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Hh+=1,T_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this.emit(Xt.FIREWALL_RESTRICTION)),t(c)},ms);T.on(E.LEAVE_SUCCESS,o,this),this.on(Xt.CONNECTION_STATE_CHANGED,s,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return 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:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=de(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(p=>{var _;return(_=p.ssrcs)==null?void 0:_.find(C=>{var y;return(y=C.value)==null?void 0:y.includes(s)})}),a,c,d;if(n.length===3)a=n[0],c=n[1],d=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[0])),c=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[1])),d=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let p=el({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:de(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(p)),d=JSON.parse(JSON.stringify(p)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${h.MAIN} ${u}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${h.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${h.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${u}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${u}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${u}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${u}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(p=>p.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return 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),s=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=de(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(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:s,smallVideo:o,auxVideo:n}=e;try{if(Hs()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let u=a[d],m;d===0&&t?m=t:d===1&&s?m=s:d===2&&o?m=o:d===3&&n&&(m=n),m&&(yield this.setSenderMaxBitrate(u,m))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),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 s,o;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=de(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 s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=de(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=de(this._peerConnection.remoteDescription.sdp));let a=re?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:re?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:re?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:re?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:re?t*1e3:t}]),s&&(n.media[2].bandwidth=[{type:a,limit:re?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:re?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:re?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:re?o*1e3:o}]);let c={type:"offer",sdp:We(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,s){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 ${s} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=We(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,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,s()}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)}
  91. 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)}
  92. next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:d,currentDirection:u,direction:m,stopped:p})=>({mid:d,currentDirection:u,direction:m,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!re||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let s=this._peerConnection.getTransceivers();t.forEach(o=>{s[o].direction!==e&&(s[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===Q.INACTIVE&&n===Q.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Q.SENDONLY&&n===Q.INACTIVE&&(this._parsedAnswer.media[o].direction=Q.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return de(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:Ph(e.sdp,this.clientAbility,this._serverAbility)})}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(s=>{var o;if(s.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=s.payloads)!=null&&o.includes(String(n.payload)))&&(s.fmtp=[],s.payloads="",s.rtp=[],s.rtcpFb=[],cr(s,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:We(this._parsedAnswer)}))})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let s=!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===h.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(d=>d.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(d=>d.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=[],cr(n,c),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:We(this._parsedAnswer)}))})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.insertableStreamsAbortMap.forEach(e=>Dt(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(s=>t[s])}};b([Ln("reconnect")],_i.prototype,"startReconnection",1),b([ui(r=>r.userId)],_i.prototype,"addDownlink",1),b([ui(r=>r)],_i.prototype,"removeDownlink",1),b([Ht(!0)],_i.prototype,"updateSDP",1);var tl=class{constructor(i){l(this,"tag");l(this,"len");l(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},il=class{constructor(i){l(this,"tinyId");l(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new tl(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},$h=new Set;function dr(){let r=Math.floor(Math.random()*4294967296);return $h.has(r)?dr():($h.add(r),r)}var Wh=Ie(Oe());var lr=class extends Wh.default{constructor(e){super();l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_currentState","DISCONNECTED");l(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=A.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(E.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 yo=class extends lr{constructor(e){super(P(N({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(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});l(this,"_flag",0);l(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:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,o=Object.keys(t).find(n=>t[n]!==s[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${s[o]} ${ri()} ${Ji()}`),v.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Z.run(Ai,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Z.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Pt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&Ti),bigVideo:!!(this.flag&gi),smallVideo:!!(this.flag&us),auxVideo:!!(this.flag&$i)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}close(e){var s;let t=((s=this._peerConnection)==null?void 0:s.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,s;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"),(s=this.singlePC)==null||s.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,u,m,p,_,C,y;if(!this.singlePC)return;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 R({code:S.NOT_SUPPORTED_H264,message:x({key:L.NOT_SUPPORTED_H264ENCODE})});pe&&ei()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ze["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_PUBLISH,responseCommand:U.SPC_PUBLISH_RESULT,data:P(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[s?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:D}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],D,t.streamType)}e&&(this[s?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(m=this.localMainVideoTrack)==null?void 0:m.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(C=this.localAuxVideoTrack)==null?void 0:C.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!s&&(this._room.preferHW||((y=this._room.scheduleResult.config)==null?void 0:y.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){if(!tt())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(),d=[],u=[],m=(_,C,y)=>{var B,ve;let D=c[C].sender.replaceTrack(y);u.push(C),(B=this.singlePC)!=null&&B.enableInsertableStreams&&D.then(()=>this.createEncodedStreams(c[C].sender,_)),(ve=this.singlePC)!=null&&ve.scriptTransformWorker&&this.initSenderTransfrom(c[C].sender,_),d.push(D)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,o?3:1,n),s&&m(8,2,s);let p=this.singlePC.setTransceiverDirection(Q.SENDONLY,u);return d.push(p),Promise.all(d)}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 s=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,u)=>{var p;let m=this.getTrackByMediaType(t);u.enqueue(((p=this.singlePC)==null?void 0:p.isUsingH264)&&m?m.encodeFrame(d,t===8):d)}}),o):s.readable).pipeTo(s.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let s=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:s,isSmall:o}))}enableSmall(e){return f(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(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=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(Q.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 f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:U.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:U.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:U.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?h.AUXILIARY:h.MAIN} stream`),Pt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Q.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Q.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?h.AUXILIARY:h.MAIN} stream`),Pt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Q.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(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(s)),o&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:W.UPDATE_MUTE_STAT,responseCommand:U.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Fi?(this._log.error(Ce.NOT_SUPPORTED_H264ENCODE),new R({code:S.NOT_SUPPORTED_H264,message:x({key:L.NOT_SUPPORTED_H264ENCODE})})):new R({code:S.UNKNOWN,message:x({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:U.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}))})}};b([It(function({localVideoTrack:r}){r==null||r.once("6",this.onVideoEncodeFailed,this)})],yo.prototype,"publish",1),b([It(function({localVideoTrack:r}){r==null||r.off("6",this.onVideoEncodeFailed,this)})],yo.prototype,"unpublish",1);var rl=yo;function Jh(r){return Object.keys(r).filter(i=>r[i])}var ts=class extends lr{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new mi(this._room,this),this.remoteVideoTrack=new At(this._room,this),this.remoteAuxiliaryTrack=new Jr(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 Ni(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){var u;let t=e.streams[0],{track:s,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let c=h.AUDIO;s.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),(u=this.singlePC)!=null&&u.scriptTransformWorker&&this.initReceiverTransform(o,a,s.kind===h.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let s=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:c=>{var d;return(d=this.singlePC)!=null&&d.isUsingH264?e.decodeFrame(c):c}};(e.enableDecodeFrame?s.readable.pipeThrough(new TransformStream({transform:(c,d)=>d.enqueue(n.enqueue(c))})):s.readable).pipeTo(s.writable,o).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,o)}}initReceiverTransform(e,t,s){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:s,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Jh(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new R({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((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"),pt&&ft<92)return;this.singlePC.startReconnection()}}unsubscribe(s){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=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Jh(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=U.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=U.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:s,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new R({code:a.code,message:x({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(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return 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 s={audioSsrc:dr(),bigVideoSsrc:dr(),bigVideoRtxSsrc:dr(),auxVideoSsrc:dr(),auxVideoRtxSsrc:dr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:U.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:s},retries:3,retryTimeout:0});if(u.data.code!==0)throw new R({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{let s=this._room.scheduleResult.config;((s==null?void 0:s.jitterDelay)||(s==null?void 0:s.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:s.jitterDelay,auxDelay:s.jitterDelayAux})}}})}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?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||si(e)&&si(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let s=this.singlePC.getReceiversByUserId(this.userId);return ee(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),ee(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,si(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o}){let n=-1;try{if(e===0&&t===0)return s.forEach(c=>c.jitterBufferTarget=0),o();if(s.forEach(c=>{var p;let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack||si(e)&&c.track===this.remoteAudioTrack.outMediaTrack;if(d&&si(t)||!d&&si(e))return;let u=d?t||0:e,m=(c.jitterBufferTarget||0)+100;m>u||(c.jitterBufferTarget=m,this._log.debug(`set ${d?"aux ":""}${(p=c==null?void 0:c.track)==null?void 0:p.kind} jitterBuffer delay ${m} -> ${u}`))}),!s.find(c=>{let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return c.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();n=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})},1e3)}catch(a){this._log.warn(`set jitterBuffer delay error: ${a}`),clearTimeout(n),o()}}};b([Ht(),J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],ts.prototype,"subscribe",1),b([Ht()],ts.prototype,"unsubscribe",1),b([ui(()=>"jitter")],ts.prototype,"setJitterBufferDelay",1);var jh=ts;function qh(){return J(r=>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;T.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Xh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Qh=Ie(Oe());function I_(){return Math.floor(Math.random()*16383)}var sl=class extends Qh.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;l(this,"log");l(this,"cmdIdSeqMap",new Map);l(this,"messageMap",new Map);this.log=A.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(U.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",s=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===s&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||I_(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(W.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let o={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${s}_${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)>sl.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),Mr(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,u)=>d.message.seq-u.message.seq);c[0]&&(o=c[0].message)}s.lastSeq!==0&&o.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${s.lastSeq} -> ${o.seq}`),s.lastSeq=o.seq,clearTimeout((a=s.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=s==null?void 0:s.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},bo=sl;l(bo,"SEQ_INTERVAL",300);var{isString:zh,isUndefined:is,getNetworkType:A_,isEmpty:No}=Ve,Rt=class extends fa{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=Pr;this._changeBigSmallRecords=new Map;this.networkQuality=null;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._updateAudioLevelTaskId=-1;this._stats=new go(this,this._log),this.userManager=new Qn(this.userId,this._log),this._version=ye,this.sdpSemantics=hr,is(e.sdpSemantics)?wt.isUnifiedPlanDefault()&&(this.sdpSemantics=Si):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${A_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=is(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Pr,!is(e.enableSPC)&&Pr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new wh(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,s){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=cl(n,[]);T.emit(E.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof R&&u.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let d=w();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:w()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){v.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new _i({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new R({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,o)=>f(this,null,function*(){var c,d,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(me.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),o(m)}),le((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Pr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);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:qa(),netType:Or(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;((u=this.scheduleResult.config)==null?void 0:u.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new R({code:S.JOIN_ROOM_FAILED,message:x({key:L.JOIN_ROOM_TIMEOUT})}))},a),T.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,n),this.signalChannel.once(U.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:p,message:_,data:C,tinyId:y}=m.data;T.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),y&&(this.tinyId=y),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=C.publishers,this.singlePC&&this.singlePC.connect(C.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new R({code:S.JOIN_ROOM_FAILED,extraCode:p,message:x({key:L.JOIN_ROOM_FAILED,data:{error:_,code:p}})})))})}))}reJoin(e=!0){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(P(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Y.logSuccessEvent({userId:this.userId,eventType:Ue.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Xt.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof rl&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Xt.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Eo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Y.logFailedEvent({userId:this.userId,eventType:Ue.REJOIN,error:t}),this.emit("error",new R({code:S.JOIN_ROOM_FAILED,message:x({key:L.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||ch(this.userId),o=!!(s&&s.isConnected&&s.keepAlive),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?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new Kr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new bo(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ui({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ui.EVENT_NETWORK_QUALITY,a=>{this.emit("network-quality",a)})),ke(this,this.signalChannel).add(me.CONNECTION_STATE_CHANGED,a=>{T.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(me.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(U.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:u}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:u})}).add(U.PEER_LEAVE,a=>{let{userId:c,reason:d=0}=a.data.data;this.userManager.deleteUser(c,d)}).add(U.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(U.CLIENT_BANNED,a=>{let c=a.data.data,{reason:d}=c;if(Y.uploadEvent({log:`stat-banned:${d}`,userId:this.userId}),d==="user_time_out"){this._log.warn(`${d} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[d==="kick"?"error":"info"](`user was banned because of [${d}]`),this.reset(),this.emit("banned",{reason:d})}),this.signalChannel.once(me.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||_e(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(E.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(W.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),this.networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Z.run(Ii,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Z.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return 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 s=(n=this.signalChannel)!=null&&n.isConnected?wu(this.userId):[],o=P(N({str_sdk_version:cs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Or()},t.msg_device_info)});if(this.heartbeatReport=o,T.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(W.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.emit("heartbeat-report",P(N({},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.map(({userId:s,srcTinyId:o,flag:n})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});T.emit(E.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 Eo&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let o=new(this.singlePC?jh:Wd)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,e),this.emit("remote-published",o)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let o=s.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",P(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Z.run(Ii,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Z.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:W.GET_USER_LIST,responseCommand:U.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw x({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:U.USER_LIST_RES,code:s,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!Bd)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)===oe.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof Ke&&!s.getIsReconnecting()){let o=s.getPeerConnection();o&&o.connectionState===oe.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Y.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Eo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}this.remotePublishedUserMap.forEach(t=>{let s=new Wd({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.subscribe(t.subscribeState,"auxiliary")})})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new R({code:S.INVALID_OPERATION,message:x({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),Z.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:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:U.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new R({code:S.SWITCH_ROLE_FAILED,message:x({key:L.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof R&&s.getCode()===S.API_CALL_TIMEOUT&&(s=new R({code:S.SWITCH_ROLE_FAILED,message:x({key:L.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return f(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Le&&(c instanceof Gt?s.audio=c:t.audio=c),c instanceof he&&(c instanceof ze&&c.mediaType===2?s.video=c:t.video=c)});let o=No(t),n=No(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new rl({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Eo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",P(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==S.ICE_TRANSPORT_ERROR&&(d===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Le&&(o instanceof Gt?s.audio=o:t.audio=o),o instanceof he&&(o instanceof ze&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");No(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),No(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.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||!fc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(E.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:h.VIDEO,videoType:h.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],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),T.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${da(n)}] prev: [${da(s.subscribeState)}]`),yield s.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof R?n.getCode():S.UNKNOWN,c=n;throw n instanceof R?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new R({code:S.API_CALL_ABORTED,message:x({key:L.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new R({code:a,message:x({key:L.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),T.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,Z.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run(fr,()=>{var o;uu()?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let s=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!s)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=Z.run(fr,()=>f(this,null,function*(){(yield s.getStats()).forEach(c=>{c.type==="media-source"&&c.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=c.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Z.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1)}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,s;let e={};return e[this.userId]=((s=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:s.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 s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(Ve.getTurnServer(o))):Ve.isPlainObject(e)&&s.push(Ve.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:U.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:U.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?U.START_PUBLISH_TENCENT_CDN_RES:U.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?U.STOP_PUBLISH_TENCENT_CDN_RES:U.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:U.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Ve.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:s,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.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=d-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${s}] to ${u.smallVideo?"small":"big"} video successfully. count ${mr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=mr}catch(m){this._log.info(`change [${s}] to ${u.smallVideo?"small":"big"} video failed. count ${mr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:mr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(zh(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!is(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new R({code:S.INVALID_PARAMETER,message:x({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(!is(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new R({code:S.INVALID_PARAMETER,message:x({key:L.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!is(e.userDefinePushArgs))if(zh(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 R({code:S.INVALID_PARAMETER,message:x({key:L.INVALID_USER_DEFINE_PUSH_ARGS})});No(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Tt)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new R({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([Kd(["left",ae.INIT],"joined"),it({settings:{retries:1,timeout:0},onRetrying(r){this._log.warn(`join retry ${r}`)},onRetryFailed(r){this._log.error("join failed",r)},onError(r,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),kt(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),i())}}),rh()],Rt.prototype,"join",1),b([Kd("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),sh(),Ln("leave room"),zs({fnName:"publish",validateArgs:!1}),zs({fnName:"unsubscribe",validateArgs:!1})],Rt.prototype,"leave",1),b([Ht(),qh(),it({settings:{retries:Yt,timeout:r=>Lt(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),T.emit(E.PUBLISH_FAILED,{room:this}))}})],Rt.prototype,"publish",1),b([zs({fnName:"publish"}),Ru("api-call"),Ht(),Xh(),It(function(){var r,i;this.localTracks.size===0&&Di()&&((i=(r=this.singlePC)==null?void 0:r.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],Rt.prototype,"unpublish",1),b([ui(r=>r.userId)],Rt.prototype,"replaceTrack",1),b([ui((...r)=>r[0].userId),wn(),oh(),it({settings:{retries:Yt,timeout:r=>Lt(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),T.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Rt.prototype,"subscribe",1),b([zs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),ui((...r)=>r[0].userId)],Rt.prototype,"unsubscribe",1);ho.create=ho._create.bind(ho,Rt);var g0=ho;export{g0 as default};