trtc-sdk-v5 5.15.0-beta.2 → 5.15.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -1,16 +1,16 @@
1
- var Y_=Object.create;var ks=Object.defineProperty,Z_=Object.defineProperties,mm=Object.getOwnPropertyDescriptor,K_=Object.getOwnPropertyDescriptors,eg=Object.getOwnPropertyNames,na=Object.getOwnPropertySymbols,pm=Object.getPrototypeOf,$d=Object.prototype.hasOwnProperty,fm=Object.prototype.propertyIsEnumerable,tg=Reflect.get;var hr=Math.pow,Hd=(o,i,e)=>i in o?ks(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,M=(o,i)=>{for(var e in i||(i={}))$d.call(i,e)&&Hd(o,e,i[e]);if(na)for(var e of na(i))fm.call(i,e)&&Hd(o,e,i[e]);return o},L=(o,i)=>Z_(o,K_(i));var aa=(o,i)=>{var e={};for(var t in o)$d.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&na)for(var t of na(o))i.indexOf(t)<0&&fm.call(o,t)&&(e[t]=o[t]);return e};var Ui=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Vi=(o,i)=>{for(var e in i)ks(o,e,{get:i[e],enumerable:!0})},ig=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of eg(i))!$d.call(o,r)&&r!==e&&ks(o,r,{get:()=>i[r],enumerable:!(t=mm(i,r))||t.enumerable});return o};var Je=(o,i,e)=>(e=o!=null?Y_(pm(o)):{},ig(i||!o||!o.__esModule?ks(e,"default",{value:o,enumerable:!0}):e,o));var O=(o,i,e,t)=>{for(var r=t>1?void 0:t?mm(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&ks(i,e,r),r};var d=(o,i,e)=>Hd(o,typeof i!="symbol"?i+"":i,e);var He=(o,i,e)=>tg(pm(o),e,i);var f=(o,i,e)=>new Promise((t,r)=>{var s=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(o,i)).next())});var at=Ui((kI,Wd)=>{"use strict";var rg=Object.prototype.hasOwnProperty,ht="~";function Ps(){}Object.create&&(Ps.prototype=Object.create(null),new Ps().__proto__||(ht=!1));function og(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function _m(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new og(e,t||o,r),n=ht?ht+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function ca(o,i){--o._eventsCount===0?o._events=new Ps:delete o._events[i]}function nt(){this._events=new Ps,this._eventsCount=0}nt.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)rg.call(e,t)&&i.push(ht?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};nt.prototype.listeners=function(i){var e=ht?ht+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};nt.prototype.listenerCount=function(i){var e=ht?ht+i:i,t=this._events[e];return t?t.fn?1:t.length:0};nt.prototype.emit=function(i,e,t,r,s,n){var a=ht?ht+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,h;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,s),!0;case 6:return c.fn.call(c.context,e,t,r,s,n),!0}for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c.fn.apply(c.context,u)}else{var m=c.length,_;for(h=0;h<m;h++)switch(c[h].once&&this.removeListener(i,c[h].fn,void 0,!0),l){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,e);break;case 3:c[h].fn.call(c[h].context,e,t);break;case 4:c[h].fn.call(c[h].context,e,t,r);break;default:if(!u)for(_=1,u=new Array(l-1);_<l;_++)u[_-1]=arguments[_];c[h].fn.apply(c[h].context,u)}}return!0};nt.prototype.on=function(i,e,t){return _m(this,i,e,t,!1)};nt.prototype.once=function(i,e,t){return _m(this,i,e,t,!0)};nt.prototype.removeListener=function(i,e,t,r){var s=ht?ht+i:i;if(!this._events[s])return this;if(!e)return ca(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&ca(this,s);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:ca(this,s)}return this};nt.prototype.removeAllListeners=function(i){var e;return i?(e=ht?ht+i:i,this._events[e]&&ca(this,e)):(this._events=new Ps,this._eventsCount=0),this};nt.prototype.off=nt.prototype.removeListener;nt.prototype.addListener=nt.prototype.on;nt.prefixed=ht;nt.EventEmitter=nt;typeof Wd!="undefined"&&(Wd.exports=nt)});var dc=Ui((oC,lp)=>{"use strict";var dp=lp.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(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.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(o){return o.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(o){return o.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(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.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(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["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(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.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(o){return o.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(o){return o.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(o){return"imageattr:%s %s %s"+(o.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(o){return"simulcast:%s %s"+(o.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(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.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(dp).forEach(function(o){var i=dp[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var mp=Ui(Yi=>{"use strict";var rs=function(o){return String(Number(o))===o?Number(o):o},hT=function(o,i,e,t){if(t&&!e)i[t]=rs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=rs(o[r+1]))},mT=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;hT(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},up=dc(),pT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Yi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(pT).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(up[s]||[]).length;a+=1){var c=up[s][a];if(c.reg.test(n))return mT(c,t,n)}}),i.media=e,i};var hp=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=rs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Yi.parseParams=function(o){return o.split(/;\s?/).reduce(hp,{})};Yi.parseFmtpConfig=Yi.parseParams;Yi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Yi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(rs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Yi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(hp,{})})};Yi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=rs(e):(t=rs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var fp=Ui((nC,pp)=>{"use strict";var Zl=dc(),fT=/%[sdv%]/g,_T=function(o){var i=1,e=arguments,t=e.length;return o.replace(fT,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},mn=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return _T.apply(null,r)},gT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],TT=["i","c","b","a"];pp.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||gT,t=i.innerOrder||TT,r=[];return e.forEach(function(s){Zl[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(mn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(mn(s,n,a))})})}),o.media.forEach(function(s){r.push(mn("m",Zl.m[0],s)),t.forEach(function(n){Zl[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(mn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(mn(n,a,c))})})})}),r.join(`\r
1
+ var Z_=Object.create;var ks=Object.defineProperty,K_=Object.defineProperties,mm=Object.getOwnPropertyDescriptor,eg=Object.getOwnPropertyDescriptors,tg=Object.getOwnPropertyNames,na=Object.getOwnPropertySymbols,pm=Object.getPrototypeOf,$d=Object.prototype.hasOwnProperty,fm=Object.prototype.propertyIsEnumerable,ig=Reflect.get;var hr=Math.pow,Hd=(o,i,e)=>i in o?ks(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,O=(o,i)=>{for(var e in i||(i={}))$d.call(i,e)&&Hd(o,e,i[e]);if(na)for(var e of na(i))fm.call(i,e)&&Hd(o,e,i[e]);return o},L=(o,i)=>K_(o,eg(i));var aa=(o,i)=>{var e={};for(var t in o)$d.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&na)for(var t of na(o))i.indexOf(t)<0&&fm.call(o,t)&&(e[t]=o[t]);return e};var Ui=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Vi=(o,i)=>{for(var e in i)ks(o,e,{get:i[e],enumerable:!0})},rg=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of tg(i))!$d.call(o,r)&&r!==e&&ks(o,r,{get:()=>i[r],enumerable:!(t=mm(i,r))||t.enumerable});return o};var Ge=(o,i,e)=>(e=o!=null?Z_(pm(o)):{},rg(i||!o||!o.__esModule?ks(e,"default",{value:o,enumerable:!0}):e,o));var M=(o,i,e,t)=>{for(var r=t>1?void 0:t?mm(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&ks(i,e,r),r};var d=(o,i,e)=>Hd(o,typeof i!="symbol"?i+"":i,e);var Pe=(o,i,e)=>ig(pm(o),e,i);var p=(o,i,e)=>new Promise((t,r)=>{var s=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(o,i)).next())});var at=Ui((PI,Wd)=>{"use strict";var og=Object.prototype.hasOwnProperty,ht="~";function Ps(){}Object.create&&(Ps.prototype=Object.create(null),new Ps().__proto__||(ht=!1));function sg(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function _m(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new sg(e,t||o,r),n=ht?ht+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function ca(o,i){--o._eventsCount===0?o._events=new Ps:delete o._events[i]}function nt(){this._events=new Ps,this._eventsCount=0}nt.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)og.call(e,t)&&i.push(ht?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};nt.prototype.listeners=function(i){var e=ht?ht+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};nt.prototype.listenerCount=function(i){var e=ht?ht+i:i,t=this._events[e];return t?t.fn?1:t.length:0};nt.prototype.emit=function(i,e,t,r,s,n){var a=ht?ht+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,s),!0;case 6:return c.fn.call(c.context,e,t,r,s,n),!0}for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c.fn.apply(c.context,u)}else{var h=c.length,_;for(m=0;m<h;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),l){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,r);break;default:if(!u)for(_=1,u=new Array(l-1);_<l;_++)u[_-1]=arguments[_];c[m].fn.apply(c[m].context,u)}}return!0};nt.prototype.on=function(i,e,t){return _m(this,i,e,t,!1)};nt.prototype.once=function(i,e,t){return _m(this,i,e,t,!0)};nt.prototype.removeListener=function(i,e,t,r){var s=ht?ht+i:i;if(!this._events[s])return this;if(!e)return ca(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&ca(this,s);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:ca(this,s)}return this};nt.prototype.removeAllListeners=function(i){var e;return i?(e=ht?ht+i:i,this._events[e]&&ca(this,e)):(this._events=new Ps,this._eventsCount=0),this};nt.prototype.off=nt.prototype.removeListener;nt.prototype.addListener=nt.prototype.on;nt.prefixed=ht;nt.EventEmitter=nt;typeof Wd!="undefined"&&(Wd.exports=nt)});var dc=Ui((sC,lp)=>{"use strict";var dp=lp.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(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.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(o){return o.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(o){return o.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(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.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(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["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(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.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(o){return o.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(o){return o.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(o){return"imageattr:%s %s %s"+(o.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(o){return"simulcast:%s %s"+(o.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(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.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(dp).forEach(function(o){var i=dp[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var mp=Ui(Yi=>{"use strict";var is=function(o){return String(Number(o))===o?Number(o):o},mT=function(o,i,e,t){if(t&&!e)i[t]=is(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=is(o[r+1]))},pT=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;mT(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},up=dc(),fT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Yi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(fT).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(up[s]||[]).length;a+=1){var c=up[s][a];if(c.reg.test(n))return pT(c,t,n)}}),i.media=e,i};var hp=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=is(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Yi.parseParams=function(o){return o.split(/;\s?/).reduce(hp,{})};Yi.parseFmtpConfig=Yi.parseParams;Yi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Yi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(is),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Yi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(hp,{})})};Yi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=is(e):(t=is(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var fp=Ui((aC,pp)=>{"use strict";var Zl=dc(),_T=/%[sdv%]/g,gT=function(o){var i=1,e=arguments,t=e.length;return o.replace(_T,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},mn=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return gT.apply(null,r)},TT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ET=["i","c","b","a"];pp.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||TT,t=i.innerOrder||ET,r=[];return e.forEach(function(s){Zl[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(mn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(mn(s,n,a))})})}),o.media.forEach(function(s){r.push(mn("m",Zl.m[0],s)),t.forEach(function(n){Zl[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(mn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(mn(n,a,c))})})})}),r.join(`\r
2
2
  `)+`\r
3
- `}});var _p=Ui(yi=>{"use strict";var io=mp(),ET=fp(),ST=dc();yi.grammar=ST;yi.write=ET;yi.parse=io.parse;yi.parseParams=io.parseParams;yi.parseFmtpConfig=io.parseFmtpConfig;yi.parsePayloads=io.parsePayloads;yi.parseRemoteCandidates=io.parseRemoteCandidates;yi.parseImageAttributes=io.parseImageAttributes;yi.parseSimulcastStreamList=io.parseSimulcastStreamList});var Qh=Ui((_B,n_)=>{"use strict";var s_=n_.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(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.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(o){return o.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(o){return o.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(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.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(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["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(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.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(o){return o.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(o){return o.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(o){return"imageattr:%s %s %s"+(o.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(o){return"simulcast:%s %s"+(o.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(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.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(s_).forEach(function(o){var i=s_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var d_=Ui(dr=>{"use strict";var vs=function(o){return String(Number(o))===o?Number(o):o},iI=function(o,i,e,t){if(t&&!e)i[t]=vs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=vs(o[r+1]))},rI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;iI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},a_=Qh(),oI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);dr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(oI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(a_[s]||[]).length;a+=1){var c=a_[s][a];if(c.reg.test(n))return rI(c,t,n)}}),i.media=e,i};var c_=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=vs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};dr.parseParams=function(o){return o.split(/;\s?/).reduce(c_,{})};dr.parseFmtpConfig=dr.parseParams;dr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};dr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(vs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};dr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(c_,{})})};dr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=vs(e):(t=vs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var u_=Ui((TB,l_)=>{"use strict";var Yh=Qh(),sI=/%[sdv%]/g,nI=function(o){var i=1,e=arguments,t=e.length;return o.replace(sI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ta=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return nI.apply(null,r)},aI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],cI=["i","c","b","a"];l_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||aI,t=i.innerOrder||cI,r=[];return e.forEach(function(s){Yh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(ta(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(ta(s,n,a))})})}),o.media.forEach(function(s){r.push(ta("m",Yh.m[0],s)),t.forEach(function(n){Yh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(ta(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(ta(n,a,c))})})})}),r.join(`\r
3
+ `}});var _p=Ui(Ri=>{"use strict";var io=mp(),ST=fp(),IT=dc();Ri.grammar=IT;Ri.write=ST;Ri.parse=io.parse;Ri.parseParams=io.parseParams;Ri.parseFmtpConfig=io.parseFmtpConfig;Ri.parsePayloads=io.parsePayloads;Ri.parseRemoteCandidates=io.parseRemoteCandidates;Ri.parseImageAttributes=io.parseImageAttributes;Ri.parseSimulcastStreamList=io.parseSimulcastStreamList});var Qh=Ui((MF,c_)=>{"use strict";var a_=c_.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(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.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(o){return o.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(o){return o.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(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.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(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["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(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.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(o){return o.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(o){return o.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(o){return"imageattr:%s %s %s"+(o.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(o){return"simulcast:%s %s"+(o.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(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.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(a_).forEach(function(o){var i=a_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var u_=Ui(dr=>{"use strict";var vs=function(o){return String(Number(o))===o?Number(o):o},rI=function(o,i,e,t){if(t&&!e)i[t]=vs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=vs(o[r+1]))},oI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;rI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},d_=Qh(),sI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);dr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(sI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(d_[s]||[]).length;a+=1){var c=d_[s][a];if(c.reg.test(n))return oI(c,t,n)}}),i.media=e,i};var l_=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=vs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};dr.parseParams=function(o){return o.split(/;\s?/).reduce(l_,{})};dr.parseFmtpConfig=dr.parseParams;dr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};dr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(vs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};dr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(l_,{})})};dr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=vs(e):(t=vs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var m_=Ui((kF,h_)=>{"use strict";var Yh=Qh(),nI=/%[sdv%]/g,aI=function(o){var i=1,e=arguments,t=e.length;return o.replace(nI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ta=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return aI.apply(null,r)},cI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],dI=["i","c","b","a"];h_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||cI,t=i.innerOrder||dI,r=[];return e.forEach(function(s){Yh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(ta(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(ta(s,n,a))})})}),o.media.forEach(function(s){r.push(ta("m",Yh.m[0],s)),t.forEach(function(n){Yh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(ta(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(ta(n,a,c))})})})}),r.join(`\r
4
4
  `)+`\r
5
- `}});var Zh=Ui(lr=>{"use strict";var Co=d_(),dI=u_();lr.write=dI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import D4 from"webrtc-adapter";var Yf=Je(at());var gm=(F=>(F[F.INVALID_PARAMETER=4096]="INVALID_PARAMETER",F[F.INVALID_OPERATION=4097]="INVALID_OPERATION",F[F.NOT_SUPPORTED=4098]="NOT_SUPPORTED",F[F.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",F[F.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",F[F.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",F[F.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",F[F.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",F[F.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",F[F.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",F[F.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",F[F.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",F[F.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",F[F.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",F[F.CLIENT_BANNED=16448]="CLIENT_BANNED",F[F.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",F[F.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",F[F.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",F[F.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",F[F.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",F[F.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",F[F.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",F[F.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",F[F.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",F[F.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",F[F.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",F[F.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",F[F.API_CALL_ABORTED=16461]="API_CALL_ABORTED",F[F.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",F[F.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",F[F.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",F[F.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",F[F.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",F[F.UNKNOWN=65535]="UNKNOWN",F))(gm||{}),I=gm;var sg=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},ws=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${sg(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},D=ws;var Gd=0,Tm=!0,da=function(o){Gd=o;let i=new Date;i.setTime(i.getTime()+o),R[Tm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),Tm=!1},Em=function(){return Gd},Bi=function(){return Date.now()+Gd},la=function(){let o=new Date;return o.setTime(Bi()),o.toLocaleString()},Do=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var vt={};Vi(vt,{REPORT_TYPE:()=>Wo,buildSSOPackage:()=>Gi,bytes2ms:()=>Om,calculateScaleResolutionDownNumber:()=>$o,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>qs,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ti,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>Bm,getConstructorName:()=>Uo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>ei,getNetworkType:()=>ba,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Kt,getStringByteLength:()=>Js,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Oe,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Bo,isArray:()=>Ae,isAudioWorkletSupported:()=>wm,isBoolean:()=>me,isConstructor:()=>jr,isEmpty:()=>Vo,isFunction:()=>ue,isLangChinese:()=>Zt,isMediaStreamTrack:()=>km,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Vt,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Ho,loadVideo:()=>Fm,ms2bytes:()=>Mm,ms2samples:()=>fl,normalizeUrl:()=>Oa,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var ol={};Vi(ol,{AUDIO_MUTE_BIT:()=>Ta,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Fr,AUX_STREAM_MSID:()=>Yd,BACKEND_ENV:()=>ga,BASE_DOC_URL:()=>ft,BASE_HOST:()=>Sm,CAPABILITIES_KEYS:()=>Ia,CLASS_NAME:()=>vg,CLOUD_CONSOLE_URL:()=>dg,CROSS_ROOM_BIT:()=>Qd,DATA_FREEZE_TIMING:()=>Sa,DOC_BILLING_CN:()=>ua,DOC_BILLING_OVERSEA:()=>ha,DOC_URL:()=>lg,DTLS_STATE_UNKNOWN:()=>Yt,ENV_NAME:()=>Fi,EXCHANGE_SDP_TIMEOUT:()=>il,IS_WORKER:()=>Oo,IS_WORKLET:()=>xs,KIBANA_EVENT:()=>Ze,LOCAL_STREAM_PUBLISH_STATE:()=>Am,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>qd,LOGGER_DOMAIN_OVERSEA:()=>jd,LOG_LEVEL:()=>zt,LOG_LEVEL_NAME:()=>Dg,MAIN_STREAM_MSID:()=>Bs,MAX_RTT:()=>$s,MICROPHONE_COMMUNICATIONS:()=>Ng,MICROPHONE_DEFAULT:()=>Wr,MUTE_ALL_BIT:()=>mg,NAME:()=>p,NETWORK_TYPE:()=>ma,NOT_SUPPORTED_H264:()=>Hr,PAUSED_RETRY_COUNT:()=>$r,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Fs,PEER_CONNECTION_STATE:()=>Re,PEER_LEAVE_REASON:()=>rl,RECOVER_CAPTURE_INTERVAL:()=>Po,REMOTE_STREAM_TYPE_AUX:()=>Kd,REMOTE_STREAM_TYPE_MAIN:()=>Zd,RENDER_FREEZE_TIMING:()=>Cg,SCHEDULE_DOMAIN:()=>$i,SCHEDULE_TIMEOUT:()=>bg,SDP_SEMANTICS_PLAN_B:()=>Mo,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>ag,SIGNAL_PING_PONG_INTERVAL:()=>hg,SIGNAL_PING_TIMEOUT:()=>ug,SIGNAL_RECONNECTION_COUNT:()=>Ig,SMALL_STAT_BIT:()=>Vs,SPEAKER_DEFAULT:()=>Hs,STORAGE_EXPIRES_TIME:()=>pa,STREAM_TYPE_BIG:()=>Rg,STREAM_TYPE_SMALL:()=>yg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ko,SYNC_USER_LIST_INTERVAL:()=>Ag,Scene:()=>Si,THIRD_HOST:()=>cg,TRANSPORT_DIRECTION:()=>se,TRTC_ERROR_ASSISTANCE:()=>Xd,TRTC_QUALITY_BAD:()=>Tg,TRTC_QUALITY_DISCONNECTED:()=>Sg,TRTC_QUALITY_EXCELLENT:()=>fg,TRTC_QUALITY_GOOD:()=>_g,TRTC_QUALITY_POOR:()=>gg,TRTC_QUALITY_UNKNOWN:()=>pg,TRTC_QUALITY_VERY_BAD:()=>Eg,UPDATE_OFFER_TIMEOUT:()=>tl,VIDEO_MUTE_BIT:()=>Ea,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>fa,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>zd,getRetryCount:()=>Hi,getScriptDir:()=>ng,innerVersion:()=>Ls,loggerProxy:()=>Us,screenProfileMap:()=>_a,setLoggerProxy:()=>Br,setRetryCount:()=>el,setVersion:()=>Jd,version:()=>$e,videoProfileMap:()=>Qt});var Ls="4.15.00.1600",$e="5.0.0";function Jd(o){$e=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Ls=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Oo=typeof importScripts!="undefined",xs=typeof registerProcessor!="undefined",ng=()=>{let o=Oo?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Us="",Br=o=>Us=o,Sm="web.sdk.qcloud.com",ag="web.sdk.tencent.cn",cg="web.sdk.cloud.tencent.cn",dg="https://console.cloud.tencent.com/trtc",ft=`https://${Sm}/trtc/webrtc/doc`,lg=`${ft}/zh-cn/`,ua="https://cloud.tencent.com/document/product/647/85386",ha="https://trtc.io/document/56025",qd="https://yun.tim.qq.com",jd="https://apisgp.my-imcloud.com",Xd="trtc_error_assistance",mr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Fi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},zt=(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))(zt||{}),ug=18e3,hg=2e3,ma={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},pa=7*24*3600*1e3,fa={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}},Qt={"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}},pr=Qt["480p_2"],zd=Qt["120p_2"],_a={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},p={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},se={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ga={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Si=(e=>(e.LIVE="live",e.RTC="rtc",e))(Si||{}),fr=1,Vs=2,Fr=4,_r=8,Ta=64,Ea=16,mg=112,Qd=128,Bs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Yd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zd=p.MAIN,Kd=p.AUXILIARY,pg=0,fg=1,_g=2,gg=3,Tg=4,Eg=5,Sg=6,Yt="unknown",Re={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Im=1/0;function el(o){Im=o}function Hi(){return Im}var Ig=30,Ze={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},Ag=1e4,tl=1e4,il=1e4,gr="unified-plan",Mo="plan-b",Hr=1028,Am=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Am||{}),Sa=500,Cg=1e3,Rg=p.BIG,yg=p.SMALL,Fs=10*1e3,$i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},bg=2e3,vg={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},$r=5,Wr="default",Hs=Wr,Ng="communications",Dg=Object.keys(zt),rl=["normal leave","timeout leave","kick","role change"],ko=10,Po=2e3,Ia=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],$s=10*1e3;var Og=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},sl=Symbol(32),nl=Symbol(16),al=Symbol(8),Ii=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Og(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(sl)}readU16(){return this.read(nl)}readU8(){return this.read(al)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===sl){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===nl){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===al){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Ii.U32=sl;Ii.U16=nl;Ii.U8=al;var Mg=128,kg=127,HI=~kg,$I=Math.pow(2,31);function cl(o){let i=new Ii;for(;o>=128;)i.malloc(1)[0]=o&255|Mg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function Aa(o,i=0){let e=new Ii,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(cl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(cl(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new Ii;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=Aa(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=Aa(o[l],c++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(cl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Ws=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function dl(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function ct(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function ll(o,i){return o[i]}function wo(o,i,e){return new TextDecoder().decode(Pg(o,i,e))}function Pg(o,i,e){return o.slice(i,i+e)}var ul=0,Ca=2654435769,Ra=16,ml=4,Lo=2,xo=7;function wg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Cm(o,i){let e=new Ws,t=wg(i,o,ul);ul=ul+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Ws;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let ae=4;ae<16;ae++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let h=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(h.length+4),h.length&&n.writeBytes(h);let m=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(m.length+2),m.length&&n.writeBytes(m);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,ie(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=Lg(g,E)),e.writeBytes(g);let C=new Uint8Array(e.data),k=C.length;return C[0]=k>>>24&255,C[1]=k>>>16&255,C[2]=k>>>8&255,C[3]=k&255,C}function Lg(o,i){let e=o.length,r=(e+1+Lo+xo)%8;r&&(r=8-r);let s=e+1+Lo+xo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),h=0;c[0]=Math.floor(Math.random()*256)&248|r,h=1;for(let _=0;_<r;_++)c[h]=Math.floor(Math.random()*256)&255,h+=1;for(let _=0;_<Lo;)if(h<8&&(c[h]=Math.floor(Math.random()*256)&255,h+=1,_+=1),h===8){hl(c,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}let m=0;for(;m<e;)if(h<8&&(c[h]=o[m],h+=1,m+=1),h===8){hl(c,i,l,u,n,a),a+=8,h=0;for(let _=0;_<8;_++)u[_]=n[a-8+_]}for(let _=0;_<xo;)if(h<8&&(c[h]=0,h+=1,_+=1),h===8){hl(c,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}return n}function hl(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];xg(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function xg(o,i,e,t){let r=ct(o,0),s=ct(o,4),n=[];for(let c=0;c<4;c++)n[c]=ct(i,c*4);let a=0;for(let c=0;c<Ra;c++)a+=Ca,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;dl(e,r,t),dl(e,s,t+4)}var bm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Vt=o=>Number(o)<14e8,Wi=function(o,i){let e;Us?e=Us:e=Vt(o)?jd:qd;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},vm="unknown";function ba(){Vg();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?Nm(t,r):vm}function Ug(){R.warn("netType changed",ba())}var Rm=!1;function Vg(){var o;Rm||(Rm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",Ug))}function Nm(o,i){if(ma[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function va(o){vm=Nm(o)}function Jr(){return ma[ba()]}function Dm(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function Om(o,i=48e3){return pl(o/4,i)}function pl(o,i=48e3){return o*1e3/i}function Mm(o,i=48e3){return fl(o,i)*4}function fl(o,i=48e3){return o*i/1e3}var _l=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Zt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);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 qr(o,i=1,e=1){return o<=1?e:qr(o-1,e,i+e)}function Kt(o){return o>8?30*1e3:qr(o)*1e3}function Oe(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ue=o=>typeof o=="function",T=o=>typeof o=="undefined",ie=o=>typeof o=="string",Q=o=>typeof o=="number",me=o=>typeof o=="boolean",yt=o=>Oe(o)==="object",Ae=o=>Oe(o)==="array",km=o=>Oe(o)==="MediaStreamTrack".toLowerCase(),Pm=o=>o.isRemote,Tr=o=>Oe(o)==="promise",jr=o=>ue(o)&&o.prototype.constructor===o,Uo=o=>jr(o)?o.prototype.constructor.name:"",wm=typeof AudioWorkletNode!="undefined",Lm=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function U(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ym=o=>+o<10?`0${o}`:o,xm=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=ym(e[1])+ym(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Bg=Object.prototype.hasOwnProperty,{toString:tA}=Object.prototype;function Vo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Bg.call(o,i))return!1;return!0}}return!1}function ei(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Fr),hasSmall:!!(o&Vs),audioMuted:!!(o&Ta),videoMuted:!!(o&Ea),audioAvailable:!!(o&_r)&&!(o&Ta),videoAvailable:!!(o&fr)&&!(o&Ea)}}function Um(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Bo(o,i=!0){if(!ie(o))return 0;let e=o.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 ti=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ti(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Gr(i[n]),r+=1)}return r};function Gr(o){if(Ae(o)){let i=[];return o.forEach((e,t)=>{i[t]=Gr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Gr(o[e])}),i}return o}var Fo=o=>{let i=[];if(Ae(o))i=[...o];else if(ie(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Vm=o=>ie(o)?document.getElementById(o):o,Fg=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},Bm=()=>Fg(new Date);function _t(o,{keysToInclude:i,keysToExclude:e}){try{if(Ae(o))return`[${o.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ae(i)&&!Ae(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ae(o[n])?JSON.parse(_t(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Gs(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),_t(o,{keysToInclude:e})}function Js(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var gl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.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},Ho=o=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ie(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Na=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},qs=o=>(Object.keys(o).forEach(i=>{Q(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ae(o[i]))&&qs(o[i])}),o);function Ke(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function Da(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Oa(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function Ma(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===p.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function $o(o,i){return o.width*o.height===i.width*i.height?1:gl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function Fm(o){return f(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function ya(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=ya(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=ya(o[t],i)}),e}return o}var Wo=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(Wo||{});function Hg(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=L(M({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Gi(o,i,e,t){try{let r=Hg(o,i,e,t),s=Aa(r);return Cm(s,e)}catch(r){return JSON.stringify(o)}}function ka(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function Pa(o){return(o&65535)>>>0}function Hm(o){return(o&4294901760)>>>0}function $m(o){let i=$g(o);return i==null?void 0:i.busiBuff}function $g(o){try{let i={},e=0;i.totalLength=ct(o,e),e+=4,i.version=ct(o,e),e+=4,i.encryption=ll(o,e),e+=1,i.uinType=ll(o,e),e+=1,i.uinLength=ct(o,e),e+=4,i.uin=i.uinLength>4?wo(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=Wg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=ct(o,e),e+=4,i.seqNo=ct(o,e),e+=4,i.retCode=ct(o,e),e+=4,i.retStrLength=ct(o,e),e+=4,i.retStr=i.retStrLength?wo(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=ct(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?wo(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=ct(o,e),e+=4,i.cookie=i.cookieLength?wo(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=ct(o,e),e+=4,i.busiBuffLength=ct(o,e),e+=4,i.busiBuff=i.busiBuffLength?wo(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Wm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Ca*Ra>>>0;for(let s=0;s<Ra;s++)t-=(e<<ml)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<ml)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Ca,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function Wg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Wm(r,i),n=s[0]&7,a=o.length-1-n-Lo-xo,c=new Uint8Array(a),l=0,u=t,h=o.slice(0,8);e=8;let m=1;m+=n;for(let g=1;g<=Lo;)if(m<8)m++,g++;else if(m===8){let E=Tl(o,e,u,h,s,i);u=E.ivPreCrypt,h=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,m=0}let _=a;for(;_>0;)if(m<8)c[l++]=s[m]^u[m],m++,_--;else if(m===8){let g=Tl(o,e,u,h,s,i);u=g.ivPreCrypt,h=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,m=0}for(let g=1;g<=xo;)if(m<8)s[m]^u[m],m++,g++;else if(m===8){if(e>=o.length)break;let E=Tl(o,e,u,h,s,i);if(!E.success)break;u=E.ivPreCrypt,h=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,m=0}return c}function Tl(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let u=0;u<8;u++)c[u]=r[u]^a[u];let l=Wm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Gm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function Ji({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:$m(new Uint8Array(l))||(Gm?Gm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function El(o){return f(this,null,function*(){let i=U(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${U()-i}ms`),a}catch(t){return e}})}var Gg=Object.prototype.hasOwnProperty;var Ai=o=>typeof o=="function",gt=o=>typeof o=="undefined";var wa=o=>typeof o=="boolean";var Sl=o=>o.isRemote;var Il=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);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 Jm(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Il(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Gg.call(o,i))return!1;return!0}}return!1}var Jg=0,qg=1,qm=2;function jg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,h=-1,m=Jg,_=(g,E)=>f(this,null,function*(){let C=n||this;try{let k=yield o.apply(C,a);u>0&&s&&s.call(this,u),u=0,g(k)}catch(k){let ae=()=>{clearTimeout(h),u=0,m=qm,E(k)},w=()=>{m!==qm&&u<(Ai(c)?c():c)?(u++,m=qg,Ai(t)&&t.call(this,u,ae),h=window.setTimeout(()=>{h=-1,_(g,E)},Ai(l)?l(u):l)):(ae(),Ai(r)&&r.call(this,k))};Ai(e)?e.call(this,{error:k,retry:w,reject:E,retryFuncArgs:a,retriedCount:u}):w()}});return new Promise(_)}}var Ci=jg;var Er=class o{constructor(i){d(this,"_parentPath");d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=wa(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:gt(i.userId)?this.userId:i.userId,sdkAppId:gt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:gt(i.type)?this.type:i.type,isLocal:gt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:gt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,gt(this.userId)||Jm(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 es={};Vi(es,{ANDROID_VERSION:()=>xa,CHROME_MAJOR_VERSION:()=>qe,CHROME_VERSION:()=>Ka,EDGE_VERSION:()=>Va,EDG_MAJOR_VERSION:()=>Cl,EDG_VERSION:()=>Ba,ELECTRON_MAJOR_VERSION:()=>Nl,FIREFOX_MAJOR_VERSION:()=>qo,FIREFOX_VERSION:()=>Ua,HUAWEI_VERSION:()=>za,IE_VERSION:()=>Zg,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>Tt,IPADQQB_VERSION:()=>ja,IS_ANDROID:()=>_e,IS_ANDROID_WEBVIEW:()=>iT,IS_ANY_SAFARI:()=>Ft,IS_CHROME:()=>Ko,IS_CHROME_OS:()=>Rl,IS_CHROMIUM_BASE:()=>We,IS_DESKTOP_IOS_CHROME:()=>kl,IS_EDG:()=>jo,IS_EDGE:()=>zr,IS_ELECTRON:()=>eT,IS_FIREFOX:()=>te,IS_HEADLESS_CHROME:()=>vl,IS_HONOR:()=>bl,IS_HUAWEI:()=>rn,IS_HUAWEIBROWSER:()=>tn,IS_IE:()=>Qm,IS_IE8:()=>Yg,IS_IOS:()=>Te,IS_IOS_13_OR_14:()=>Ml,IS_IOS_15_1:()=>Ol,IS_IOS_CHROME:()=>js,IS_IPAD:()=>Jo,IS_IPADQQB:()=>Zs,IS_IPAD_PRO:()=>Al,IS_IPHONE:()=>Sr,IS_IPOD:()=>zm,IS_LINUX:()=>Ks,IS_LOCAL:()=>si,IS_MAC:()=>oi,IS_MACQQB:()=>Ys,IS_MIBROWSER:()=>en,IS_MQQB:()=>zo,IS_NATIVE_ANDROID:()=>Qg,IS_OLD_ANDROID:()=>zg,IS_OPENHARMONY:()=>Yo,IS_OPPOBROWSER:()=>Qo,IS_SAFARI:()=>Pe,IS_SAFARI_15_1:()=>rT,IS_SAMSUNGBROWSER:()=>on,IS_SOGOU:()=>zs,IS_SOGOUM:()=>Xs,IS_TBS:()=>ri,IS_UCBROWSER:()=>yl,IS_VIVOBROWSER:()=>sn,IS_WECHAT:()=>ji,IS_WIN:()=>Qr,IS_WQQB:()=>Qs,IS_WX:()=>Kg,IS_X5MQQB:()=>Xo,IS_XWEB:()=>qi,MACQQB_VERSION:()=>qa,MI_VERSION:()=>Xa,MQQB_VERSION:()=>Go,OPENHARMONY_VERSION:()=>tT,OPPO_VERSION:()=>Ya,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>Qa,SOGOUM_VERSION:()=>Fa,SOGOU_VERSION:()=>Ha,TBS_VERSION:()=>$a,UA_DATA_STRING:()=>ii,USER_AGENT:()=>Bt,VIVO_VERSION:()=>Za,WECHAT_VERSION:()=>Ga,WQQB_VERSION:()=>Ja,XWEB_VERSION:()=>Wa,browserInfo:()=>Ri,getBrowserCoreNumber:()=>wl,getBrowserInfo:()=>Ym,getChromeMajorVersion:()=>Zo,getDeviceModel:()=>ni,getDeviceModelFromUA:()=>ec,getGPUInfo:()=>Pl,getOSName:()=>tc,getOSNumber:()=>Zr,getOSString:()=>ai,getOSType:()=>oT,getTerminalType:()=>Ll,getUserAgentData:()=>Yr,isLocalStorageEnabled:()=>zi,isMobile:()=>an,isVersionLargerThan:()=>Dl,isVersionSmallerThan:()=>nn});var Bt=typeof navigator=="undefined"?"":navigator.userAgent,K=o=>new RegExp(o,"i").test(Bt),we=o=>{if(K(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Bt.match(i);if(e&&e[1])return e[1]}return""},La=o=>{if(K(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Bt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},jm=/AppleWebKit\/([\d.]+)/i.exec(Bt),Xg=jm?parseFloat(jm[1]):NaN,Jo=K("iPad"),Al=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&K("Macintosh"),Sr=K("iPhone")&&!Jo,zm=K("iPod"),Te=Sr||Jo||zm||Al,_e=K("Android"),xa=function(){if(_e){let o=Bt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),zg=_e&&K("webkit")&&xa<2.3,Qg=_e&&xa<5&&Xg<537,te=K("Firefox"),Ua=we("Firefox"),qo=La("Firefox"),zr=K("Edge"),Va=we("Edge"),jo=K("Edg"),Ba=we("Edg"),Cl=La("Edg"),Xs=K("SogouMobileBrowser"),Fa=we("SogouMobileBrowser"),zs=K("MetaSr\\s"),Ha=we("MetaSr\\s"),ri=K("TBS"),$a=we("TBS"),qi=K("XWEB"),Wa=we("XWEB"),Yg=K("MSIE\\s8\\.0"),Qm=K("MSIE\\/\\d+"),Zg=function(){if(Qm){let o=/MSIE\s(\d+)\.\d/.exec(Bt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Bt)&&/rv:11.0/.test(Bt)&&(i=11),i}return NaN}(),ji=K("(micromessenger|webbrowser)"),Ga=we("MicroMessenger"),Xo=!ri&&K("MQQBrowser")&&K("COVC"),zo=!ri&&K("MQQBrowser")&&!K("COVC"),Go=zo||Xo?we("MQQBrowser"):"",Qs=!ri&&K(" QQBrowser"),Ja=we(" QQBrowser"),Ys=!ri&&K("QQBrowserLite"),qa=we("QQBrowserLite"),Zs=!ri&&K("MQBHD"),ja=we("MQBHD"),Qr=K("Windows"),oi=!Te&&K("MAC OS X"),Ks=!_e&&K("Linux"),Rl=K("CrOS"),Kg=K("MicroMessenger"),yl=K("UCBrowser"),eT=K("Electron"),en=K("MiuiBrowser"),Xa=we("MiuiBrowser"),tn=K("HuaweiBrowser"),rn=K("Huawei")||K("HUAWEI"),bl=K("Honor")||K("HONOR"),za=we("HuaweiBrowser"),on=K("SamsungBrowser"),Qa=we("SamsungBrowser"),Qo=K("HeyTapBrowser"),Ya=we("HeyTapBrowser"),sn=K("VivoBrowser"),Za=we("VivoBrowser"),Yo=K("OpenHarmony"),tT=we("OpenHarmony"),Zo=()=>La("Chrome"),js=K("CriOS"),We=K("Chrome"),Ko=!zr&&!zs&&!Xs&&!ri&&!qi&&!jo&&!Qs&&!en&&!tn&&!on&&!Qo&&!sn&&We,vl=K("HeadlessChrome"),qe=Zo(),Ka=we("Chrome"),Nl=La("Electron"),Pe=!We&&!zo&&!Xo&&!Ys&&!Zs&&K("Safari"),Ft=Pe||Te,Xi=we("Version"),iT=/Android.*(wv|.0.0.0)/.test(Bt),Tt=(()=>{if(Al)return Xi;if(Te){let o=Bt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function nn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function Dl(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(Tt.split(".")[0]),rT=Xi==="15.1",Ol=Tt==="15.1",Ml=(()=>{let o=Number(Tt.split(".")[0]);return o===14||o===13})(),kl=js&&Xi==="11.1.1",si=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),Ri=Ym();function Ym(){let o=new Map([[te,["Firefox",Ua]],[jo,["Edg",Ba]],[Ko,["Chrome",Ka]],[js,["ChiOS",we("CriOS")]],[Pe&&!js,["Safari",Xi]],[ri,["TBS",$a]],[qi,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",Ja]],[zo,["QQ(Mobile)",Go]],[Xo,["QQ(Mobile X5)",Go]],[Ys,["QQ(Mac)",qa]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[Qo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Fa]],[zs,["Sogou",Ha]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var pe=null;function an(){return pe&&typeof pe.mobile=="boolean"?pe.mobile:_e||Te||Sr||Jo||Yo}var ii="";function Yr(){return f(this,null,function*(){if(pe)return pe;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return pe=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),pe&&!ii&&(ii=`UAData: ${pe.platform}/${pe.platformVersion}`,pe.architecture&&pe.bitness&&(ii+=` ${pe.architecture}/${pe.bitness}`),pe.mobile&&(ii+=" mobile"),pe.model&&(ii+=` model: ${pe.model.replace(/\s+/g,"/")}`),pe.fullVersionList&&(ii+=` ${pe.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),pe}catch(o){return null}})}function Pl(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function ni(){return(pe==null?void 0:pe.model)||ec()||""}function ec(){let o=/;\s*([^;)]+)\s+Build\//,i=Bt.match(o);return i!=null&&i[1]?i[1].trim():null}var Xm=new Map([[_e,"Android"],[Te,"iOS"],[Qr,"Windows"],[oi,"MacOS"],[Ks,"Linux"],[Rl,"ChromeOS"]]),tc=function(){return Xm.get(!0)?Xm.get(!0):pe?pe.platform:"unknown"};function Zr(){return Qr?1:_e?2:oi?3:Te?4:Ks?5:Rl?6:Yo?7:0}function wl(){return ji||qi?4:We?1:Pe?2:te?3:0}var ai=()=>{let o=tc();return pe!=null&&pe.platformVersion?o+=`/${pe.platformVersion}`:Te?o+=`/${Tt}`:_e&&(o+=`/${xa}`),o+=`/${Ri.name}/${Pe&&!js?Ri.version:Ri.version.split(".")[0]}`,pe!=null&&pe.architecture&&(o+=`/${pe.architecture}`),o};function Ll(){return _e?4:Sr?2:Jo?3:oi?12:Qr?5:Ks?13:Yo?22:1}function oT(){return _e?"Android":Sr?"iPhone":Jo?"iPad":oi?"Mac":Qr?"Windows":Ks?"Linux":"unknown"}var Zm=Je(at(),1),sT=new Zm.default,S=sT;var mt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.LOCAL_AUDIO_STARTED="113",W.LOCAL_AUDIO_STOPPED="114",W.REMOTE_AUDIO_STARTED="115",W.REMOTE_AUDIO_STOPPED="116",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.AUDIO_CONTEXT_LONG_SUSPENDED="155",W.REMOTE_VIDEO_PLAY_START="156",W.REMOTE_VIDEO_PLAY_FINISH="157",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AUDIO_PROCESSOR_DEBUG="265",W.SSO_SWITCH="266",W.SWITCH_ROOM_START="401",W.SWITCH_ROOM_SUCCESS="407",W.SWITCH_ROOM_FAILED="408",W))(mt||{});var A=mt;var xl=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ir=new xl;var nT="%cTRTC%c%s",aT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",cT="display: inline",ic=class ic{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Oo&&!xs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(A.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&zt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(A.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(A.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(ie(t.userId)&&Q(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:la(),sdkAppId:String(a),userId:n,version:$e,log:c.map(m=>m.log).join(`
6
- `)},u=JSON.stringify(l),h=Ir.enable?Gi(l,2002,a):u;yield this.uploadLogWithRetry(h,a,h instanceof Uint8Array,u),c.forEach(m=>m.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return Ci({retryFunction:()=>Ji({url:Wi(e,mr.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(Ir.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(Bi()),`[${Do(e)}] <${zt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(zt[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(ie(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};S.emit(A.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=zt[i])==null?void 0:a.toLowerCase())||"info";ic.PRINT_LOG_TAG?console[n](nT,aT,cT,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){if(i.parent instanceof Er){let e=i,{parent:t}=e,r=aa(e,["parent"]),s=new Er(r);return s.bindParent(t),s}return new Er(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;zt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(ic,"PRINT_LOG_TAG",!(Te||_e||vl));var Ul=ic,R=new Ul;var dT=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},cn=dT;var Vl=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!zi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(zi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!zi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){R.warn(e)}}setItem(i,e){if(zi())try{let t={expiresIn:Date.now()+pa,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!zi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(zi())try{localStorage.clear()}catch(i){R.warn(i)}}},ts=new Vl;var vi={};Vi(vi,{HTTPS_API:()=>kT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>du,IS_GET_CAPABILITIES_SUPPORTED:()=>cu,IS_GET_SETTINGS_SUPPORTED:()=>bi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>au,IS_INSERTABLE_STREAM_SUPPORTED:()=>mi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Sc,IS_RTC_RTP_SENDER_SUPPORTED:()=>gn,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>ns,IS_SEI_SUPPORTED:()=>En,IS_SPC_SUPPORTED:()=>ss,basis:()=>LT,capabilityCheck:()=>hu,checkSystemRequirementsInternal:()=>_c,decodeSupportStatus:()=>fc,detectVideoCodecCapabilities:()=>mu,detectVideoDecoderCapabilities:()=>Op,detectVideoEncoderCapabilities:()=>Dp,encodeSupportStatus:()=>su,getBrowserInfo:()=>yT,getDisplayResolution:()=>Ip,getH264ProfileLevelIds:()=>Mp,isAddTransceiverSupported:()=>St,isBrowserSupported:()=>ou,isCanvasCaptureStreamAPISupported:()=>Rp,isCanvasSmallStreamSupported:()=>gc,isGetReceiversSupported:()=>oo,isGetSendersSupported:()=>Rr,isGetTransceiversSupported:()=>yr,isGetUserMediaSupported:()=>Ap,isMediaDevicesSupported:()=>pc,isMediaSessionSupported:()=>bp,isMediaStreamTrackGeneratorSupported:()=>bT,isMediaStreamTrackProcessorSupported:()=>fn,isReplaceTrackSupported:()=>nu,isRequestVideoFrameCallbackSupported:()=>Ki,isSIMDSupported:()=>uu,isScaleResolutionDownBySupported:()=>yp,isScreenCaptureApiAvailable:()=>_n,isSelectedCandidatePair:()=>Cr,isSetParametersSupported:()=>Tn,isSetSinkIdSupported:()=>DT,isSmallStreamSupported:()=>Tc,isStopTransceiverSupported:()=>wT,isTRTCSupported:()=>NT,isUnifiedPlanDefault:()=>PT,isUsedInHttpProtocol:()=>Zi,isWebAudioSupported:()=>Cp,isWebCodecSupported:()=>Ec,isWebCodecsSupported:()=>pn,isWebRTCSupported:()=>lu,isWebTransportSupported:()=>vp});var Yl={};Vi(Yl,{AUDIO_LEVEL_SCALE:()=>Dt,AlphaStitchingType:()=>hn,AudioCodecPipelineType:()=>ln,AudioDecoderDowngradeState:()=>$l,AudioPlayerMode:()=>ql,AudioType:()=>ip,BASIC_TYPE:()=>Qi,BannedReason:()=>jl,CONNECTION_CLOSED_REASON:()=>Fl,CheckPermissionType:()=>Ql,ClientEvent:()=>Km,CodecType:()=>ap,ConnectionEvent:()=>ci,ConnectionState:()=>Nt,DECODE_FAILED_ERROR_CODE:()=>zl,DenoiserMode:()=>Xl,DeviceType:()=>cc,FacingMode:()=>sc,FrameWorkType:()=>rc,LeaveReason:()=>np,LocalTrackEvent:()=>Kr,MULTI_VIDEO_DATA_TYPE:()=>ui,MediaType:()=>Ve,MediaTypeLabel:()=>lT,MonitorEventId:()=>dn,MutedFlag:()=>tp,NetworkQualityValue:()=>Jl,PlayerState:()=>Ar,ReceiveMode:()=>sp,RemoteStreamType:()=>Et,RemoteTrackEvent:()=>eo,RoomEvent:()=>di,SMALL_MODE:()=>un,SceneNumber:()=>Hl,StreamEvent:()=>ep,StreamType:()=>op,SubscribeMediaType:()=>Bl,TIMER_TYPE:()=>hi,TRACK_ACTION:()=>Gl,TRACK_KIND:()=>Wl,TrackEvent:()=>li,UserRole:()=>lt,UserRoleNumber:()=>to,VideoCodec:()=>Ht,VideoCodecPipelineType:()=>ac,VideoContentHint:()=>is,VideoDecoderDowngradeState:()=>oc,VideoPlayerMode:()=>nc,VideoType:()=>rp});var rc=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(rc||{}),ci=(E=>(E.TRACK_ADDED="track-added",E.TRACK_UPDATED="track-updated",E.TRACK_SUBSCRIBED="track-subscribed",E.STREAM_ADDED="stream-added",E.STREAM_REMOVED="stream-removed",E.STREAM_UPDATED="stream-updated",E.STREAM_PUBLISHED="stream-published",E.STREAM_SUBSCRIBED="stream-subscribed",E.STREAM_UNSUBSCRIBED="stream-unsubscribed",E.STATE_CHANGED="state-changed",E.ERROR="error",E.CONNECTION_STATE_CHANGED="connection-state-changed",E.FIREWALL_RESTRICTION="firewall-restriction",E.SEI_MESSAGE="sei-message",E.CLOSED="closed",E))(ci||{}),Fl=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(Fl||{}),Km=(C=>(C.STREAM_ADDED="stream-added",C.STREAM_REMOVED="stream-removed",C.STREAM_UPDATED="stream-updated",C.STREAM_SUBSCRIBED="stream-subscribed",C.CONNECTION_STATE_CHANGED="connection-state-changed",C.PEER_JOIN="peer-join",C.PEER_LEAVE="peer-leave",C.MUTE_AUDIO="mute-audio",C.MUTE_VIDEO="mute-video",C.UNMUTE_AUDIO="unmute-audio",C.UNMUTE_VIDEO="unmute-video",C.CLIENT_BANNED="client-banned",C.NETWORK_QUALITY="network-quality",C.AUDIO_VOLUME="audio-volume",C.SEI_MESSAGE="sei-message",C.ERROR="error",C))(Km||{}),ep=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(ep||{}),Kr=(c=>(c.DEVICE_AUTO_RECOVERED="1",c.DEVICE_RECOVER_FAILED="5",c.DEVICE_CHANGED="2",c.ERROR="3",c.PUBLISH_STATE_CHANGED="4",c.ENCODE_FAILED="6",c.TRACK_ENDED="7",c.RENDER="render",c))(Kr||{}),Ar=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Ar||{}),di=(y=>(y.PEER_JOIN="peer-join",y.PEER_LEAVE="peer-leave",y.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",y.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",y.BANNED="banned",y.NETWORK_QUALITY="network-quality",y.AUDIO_VOLUME="audio-volume",y.SEI_MESSAGE="sei-message",y.ERROR="error",y.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",y.REMOTE_PUBLISHED="remote-published",y.REMOTE_UNPUBLISHED="remote-unpublished",y.FIREWALL_RESTRICTION="firewall-restriction",y.HEARTBEAT_REPORT="heartbeat-report",y.CUSTOM_MESSAGE="custom-message",y.LAYER_DATA="layerData",y.FIRST_VIDEO_FRAME="first-video-frame",y.DUMP="dump",y.AUDIO_FRAME="audio-frame",y.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",y.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",y.NTP_TIME_UPDATED="ntp-time-updated",y))(di||{}),li=(c=>(c.PLAYER_STATE_CHANGED="player-state-changed",c.MUTE="mute",c.UNMUTE="unmute",c.ERROR="error",c.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",c.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",c.FIRST_VIDEO_FRAME="first-video-frame",c.VIDEO_SIZE_CHANGED="video-size-changed",c))(li||{}),eo=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(eo||{}),tp=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(tp||{}),Hl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Hl||{}),to=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(to||{}),lt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(lt||{}),Nt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Nt||{}),$l=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))($l||{}),oc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(oc||{}),Wl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Wl||{}),Gl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Gl||{}),Ve=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(Ve||{}),lT={1:"audio",2:"auxVideo",4:"video"},ip=(i=>(i[i.opus=111]="opus",i))(ip||{}),rp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(rp||{}),op=(e=>(e.Big="big",e.Small="small",e))(op||{}),Et=(e=>(e.Main="main",e.Aux="auxiliary",e))(Et||{}),ui=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(ui||{}),dn=(P=>(P[P.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",P[P.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",P[P.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",P[P.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",P[P.MUTE_AUDIO=32772]="MUTE_AUDIO",P[P.MUTE_VIDEO=32773]="MUTE_VIDEO",P[P.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",P[P.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",P[P.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",P[P.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",P[P.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",P[P.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",P[P.SWITCH_CAMERA=32780]="SWITCH_CAMERA",P[P.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",P[P.REPLACE_VIDEO=32782]="REPLACE_VIDEO",P[P.REPLACE_AUDIO=32783]="REPLACE_AUDIO",P[P.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",P[P.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",P[P.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",P[P.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",P[P.JOIN=32788]="JOIN",P[P.LEAVE=32789]="LEAVE",P[P.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",P[P.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",P[P.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",P[P.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",P[P.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",P[P.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",P[P.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",P[P.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",P[P.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",P[P.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",P[P.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",P[P.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",P[P.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",P[P.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",P[P.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",P[P.PUBLISH_AUX=32805]="PUBLISH_AUX",P[P.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",P[P.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",P[P.VIDEO_ENCODER=4004]="VIDEO_ENCODER",P[P.VIDEO_DECODER=4005]="VIDEO_DECODER",P))(dn||{}),Jl=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(Jl||{}),sp=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(sp||{}),sc=(e=>(e.user="user",e.environment="environment",e))(sc||{}),nc=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(nc||{}),ql=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(ql||{}),jl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(jl||{}),np=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(np||{}),Dt=1e8,Xl=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Xl||{}),Bl=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Qi||{}),Ht=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Ht||{}),ac=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ac||{}),ln=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ln||{}),ap=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(ap||{}),zl=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.FAILED=1]="FAILED",m[m.WEBCODEC_INIT=2]="WEBCODEC_INIT",m[m.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",m[m.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",m[m.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",m[m.WASM_INIT=6]="WASM_INIT",m[m.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",m[m.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",m[m.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",m[m.TEST=10]="TEST",m[m.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",m))(zl||{}),is=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(is||{}),hi=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(hi||{}),un=(e=>(e.CANVAS="canvas",e.API="api",e))(un||{}),Ql=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(Ql||{}),cc=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(cc||{}),hn=(t=>(t[t.none=0]="none",t[t.horizontal=1]="horizontal",t[t.vertical=2]="vertical",t))(hn||{});var B={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"},je={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.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(o){return`exchange sdp failed ${o.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(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' 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:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.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(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} 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:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},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(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.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(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' 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(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||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(o){return`'${o}' 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:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.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(o){return`${o}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(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"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:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!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:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.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:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var cp=(o,i)=>i?`${ft}/${o}/${i}`:`${ft}/${o}/index.html`;var uT=()=>{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 o=localStorage==null?void 0:localStorage.getItem(Xd);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.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 H(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";ue(je[i])?s=je[i](e):ie(je[i])&&(s=je[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=uT();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ue(l[i])?a=l[i](e):ie(l[i])&&(a=l[i]));let u=s;return Zt()&&(c&&c[i]&&(ue(c[i])?n=c[i](e):ie(c[i])&&(n=c[i])),n&&(r?u=`${n}
5
+ `}});var Zh=Ui(lr=>{"use strict";var Co=u_(),lI=m_();lr.write=lI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import x4 from"webrtc-adapter";var Kf=Ge(at());var gm=(B=>(B[B.INVALID_PARAMETER=4096]="INVALID_PARAMETER",B[B.INVALID_OPERATION=4097]="INVALID_OPERATION",B[B.NOT_SUPPORTED=4098]="NOT_SUPPORTED",B[B.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",B[B.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",B[B.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",B[B.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",B[B.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",B[B.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",B[B.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",B[B.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",B[B.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",B[B.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",B[B.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",B[B.CLIENT_BANNED=16448]="CLIENT_BANNED",B[B.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",B[B.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",B[B.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",B[B.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",B[B.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",B[B.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",B[B.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",B[B.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",B[B.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",B[B.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",B[B.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",B[B.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",B[B.API_CALL_ABORTED=16461]="API_CALL_ABORTED",B[B.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",B[B.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",B[B.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",B[B.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",B[B.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",B[B.UNKNOWN=65535]="UNKNOWN",B))(gm||{}),I=gm;var ng=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},ws=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${ng(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},D=ws;var Gd=0,Tm=!0,da=function(o){Gd=o;let i=new Date;i.setTime(i.getTime()+o),R[Tm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),Tm=!1},Em=function(){return Gd},Fi=function(){return Date.now()+Gd},la=function(){let o=new Date;return o.setTime(Fi()),o.toLocaleString()},No=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var vt={};Vi(vt,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var ol={};Vi(ol,{AUDIO_MUTE_BIT:()=>Ta,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Br,AUX_STREAM_MSID:()=>Yd,BACKEND_ENV:()=>ga,BASE_DOC_URL:()=>ft,BASE_HOST:()=>Sm,CAPABILITIES_KEYS:()=>Ia,CLASS_NAME:()=>Ng,CLOUD_CONSOLE_URL:()=>lg,CROSS_ROOM_BIT:()=>Qd,DATA_FREEZE_TIMING:()=>Sa,DOC_BILLING_CN:()=>ua,DOC_BILLING_OVERSEA:()=>ha,DOC_URL:()=>ug,DTLS_STATE_UNKNOWN:()=>Qt,ENV_NAME:()=>Bi,EXCHANGE_SDP_TIMEOUT:()=>il,IS_WORKER:()=>Do,IS_WORKLET:()=>xs,KIBANA_EVENT:()=>Ze,LOCAL_STREAM_PUBLISH_STATE:()=>Am,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>Jd,LOGGER_DOMAIN_OVERSEA:()=>jd,LOG_LEVEL:()=>Xt,LOG_LEVEL_NAME:()=>Mg,MAIN_STREAM_MSID:()=>Fs,MAX_RTT:()=>$s,MICROPHONE_COMMUNICATIONS:()=>Dg,MICROPHONE_DEFAULT:()=>Wr,MUTE_ALL_BIT:()=>pg,NAME:()=>f,NETWORK_TYPE:()=>ma,NOT_SUPPORTED_H264:()=>Hr,PAUSED_RETRY_COUNT:()=>$r,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Bs,PEER_CONNECTION_STATE:()=>Ce,PEER_LEAVE_REASON:()=>rl,RECOVER_CAPTURE_INTERVAL:()=>ko,REMOTE_STREAM_TYPE_AUX:()=>Kd,REMOTE_STREAM_TYPE_MAIN:()=>Zd,RENDER_FREEZE_TIMING:()=>Rg,SCHEDULE_DOMAIN:()=>$i,SCHEDULE_TIMEOUT:()=>vg,SDP_SEMANTICS_PLAN_B:()=>Mo,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>cg,SIGNAL_PING_PONG_INTERVAL:()=>mg,SIGNAL_PING_TIMEOUT:()=>hg,SIGNAL_RECONNECTION_COUNT:()=>Ag,SMALL_STAT_BIT:()=>Vs,SPEAKER_DEFAULT:()=>Hs,STORAGE_EXPIRES_TIME:()=>pa,STREAM_TYPE_BIG:()=>yg,STREAM_TYPE_SMALL:()=>bg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Oo,SYNC_USER_LIST_INTERVAL:()=>Cg,Scene:()=>Ei,THIRD_HOST:()=>dg,TRANSPORT_DIRECTION:()=>ne,TRTC_ERROR_ASSISTANCE:()=>Xd,TRTC_QUALITY_BAD:()=>Eg,TRTC_QUALITY_DISCONNECTED:()=>Ig,TRTC_QUALITY_EXCELLENT:()=>_g,TRTC_QUALITY_GOOD:()=>gg,TRTC_QUALITY_POOR:()=>Tg,TRTC_QUALITY_UNKNOWN:()=>fg,TRTC_QUALITY_VERY_BAD:()=>Sg,UPDATE_OFFER_TIMEOUT:()=>tl,VIDEO_MUTE_BIT:()=>Ea,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>fa,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>zd,getRetryCount:()=>Hi,getScriptDir:()=>ag,innerVersion:()=>Ls,loggerProxy:()=>Us,screenProfileMap:()=>_a,setLoggerProxy:()=>Fr,setRetryCount:()=>el,setVersion:()=>qd,version:()=>He,videoProfileMap:()=>zt});var Ls="4.15.00.1600",He="5.0.0";function qd(o){He=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Ls=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Do=typeof importScripts!="undefined",xs=typeof registerProcessor!="undefined",ag=()=>{let o=Do?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Us="",Fr=o=>Us=o,Sm="web.sdk.qcloud.com",cg="web.sdk.tencent.cn",dg="web.sdk.cloud.tencent.cn",lg="https://console.cloud.tencent.com/trtc",ft=`https://${Sm}/trtc/webrtc/doc`,ug=`${ft}/zh-cn/`,ua="https://cloud.tencent.com/document/product/647/85386",ha="https://trtc.io/document/56025",Jd="https://yun.tim.qq.com",jd="https://apisgp.my-imcloud.com",Xd="trtc_error_assistance",mr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Bi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Xt=(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))(Xt||{}),hg=18e3,mg=2e3,ma={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},pa=7*24*3600*1e3,fa={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}},zt={"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}},pr=zt["480p_2"],zd=zt["120p_2"],_a={"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}},f={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",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ne={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ga={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ei=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ei||{}),fr=1,Vs=2,Br=4,_r=8,Ta=64,Ea=16,pg=112,Qd=128,Fs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Yd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zd=f.MAIN,Kd=f.AUXILIARY,fg=0,_g=1,gg=2,Tg=3,Eg=4,Sg=5,Ig=6,Qt="unknown",Ce={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Im=1/0;function el(o){Im=o}function Hi(){return Im}var Ag=30,Ze={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},Cg=1e4,tl=1e4,il=1e4,gr="unified-plan",Mo="plan-b",Hr=1028,Am=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Am||{}),Sa=500,Rg=1e3,yg=f.BIG,bg=f.SMALL,Bs=10*1e3,$i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},vg=2e3,Ng={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},$r=5,Wr="default",Hs=Wr,Dg="communications",Mg=Object.keys(Xt),rl=["normal leave","timeout leave","kick","role change"],Oo=10,ko=2e3,Ia=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],$s=10*1e3;var Og=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},sl=Symbol(32),nl=Symbol(16),al=Symbol(8),Si=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Og(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(sl)}readU16(){return this.read(nl)}readU8(){return this.read(al)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===sl){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===nl){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===al){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Si.U32=sl;Si.U16=nl;Si.U8=al;var kg=128,Pg=127,$I=~Pg,WI=Math.pow(2,31);function cl(o){let i=new Si;for(;o>=128;)i.malloc(1)[0]=o&255|kg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function Aa(o,i=0){let e=new Si,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(cl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(cl(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new Si;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=Aa(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=Aa(o[l],c++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(cl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Ws=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function dl(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function ct(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function ll(o,i){return o[i]}function Po(o,i,e){return new TextDecoder().decode(wg(o,i,e))}function wg(o,i,e){return o.slice(i,i+e)}var ul=0,Ca=2654435769,Ra=16,ml=4,wo=2,Lo=7;function Lg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Cm(o,i){let e=new Ws,t=Lg(i,o,ul);ul=ul+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Ws;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let re=4;re<16;re++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let m=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let h=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(h.length+2),h.length&&n.writeBytes(h);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,ie(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=xg(g,E)),e.writeBytes(g);let A=new Uint8Array(e.data),k=A.length;return A[0]=k>>>24&255,A[1]=k>>>16&255,A[2]=k>>>8&255,A[3]=k&255,A}function xg(o,i){let e=o.length,r=(e+1+wo+Lo)%8;r&&(r=8-r);let s=e+1+wo+Lo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),m=0;c[0]=Math.floor(Math.random()*256)&248|r,m=1;for(let _=0;_<r;_++)c[m]=Math.floor(Math.random()*256)&255,m+=1;for(let _=0;_<wo;)if(m<8&&(c[m]=Math.floor(Math.random()*256)&255,m+=1,_+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}let h=0;for(;h<e;)if(m<8&&(c[m]=o[h],m+=1,h+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let _=0;_<8;_++)u[_]=n[a-8+_]}for(let _=0;_<Lo;)if(m<8&&(c[m]=0,m+=1,_+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}return n}function hl(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];Ug(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function Ug(o,i,e,t){let r=ct(o,0),s=ct(o,4),n=[];for(let c=0;c<4;c++)n[c]=ct(i,c*4);let a=0;for(let c=0;c<Ra;c++)a+=Ca,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;dl(e,r,t),dl(e,s,t+4)}var bm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ut=o=>Number(o)<14e8,Wi=function(o,i){let e;Us?e=Us:e=Ut(o)?jd:Jd;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},vm="unknown";function ba(){Fg();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?Nm(t,r):vm}function Vg(){R.warn("netType changed",ba())}var Rm=!1;function Fg(){var o;Rm||(Rm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",Vg))}function Nm(o,i){if(ma[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function va(o){vm=Nm(o)}function qr(){return ma[ba()]}function Dm(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function Mm(o,i=48e3){return pl(o/4,i)}function pl(o,i=48e3){return o*1e3/i}function Om(o,i=48e3){return fl(o,i)*4}function fl(o,i=48e3){return o*i/1e3}var _l=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Yt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);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 Jr(o,i=1,e=1){return o<=1?e:Jr(o-1,e,i+e)}function Zt(o){return o>8?30*1e3:Jr(o)*1e3}function Me(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var le=o=>typeof o=="function",T=o=>typeof o=="undefined",ie=o=>typeof o=="string",z=o=>typeof o=="number",he=o=>typeof o=="boolean",yt=o=>Me(o)==="object",Ie=o=>Me(o)==="array",km=o=>Me(o)==="MediaStreamTrack".toLowerCase(),Pm=o=>o.isRemote,Tr=o=>Me(o)==="promise",jr=o=>le(o)&&o.prototype.constructor===o,xo=o=>jr(o)?o.prototype.constructor.name:"",wm=typeof AudioWorkletNode!="undefined",Lm=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function U(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ym=o=>+o<10?`0${o}`:o,xm=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=ym(e[1])+ym(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Bg=Object.prototype.hasOwnProperty,{toString:iA}=Object.prototype;function Uo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Bg.call(o,i))return!1;return!0}}return!1}function Kt(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Br),hasSmall:!!(o&Vs),audioMuted:!!(o&Ta),videoMuted:!!(o&Ea),audioAvailable:!!(o&_r)&&!(o&Ta),videoAvailable:!!(o&fr)&&!(o&Ea)}}function Um(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Vo(o,i=!0){if(!ie(o))return 0;let e=o.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 ei=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ei(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Gr(i[n]),r+=1)}return r};function Gr(o){if(Ie(o)){let i=[];return o.forEach((e,t)=>{i[t]=Gr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Gr(o[e])}),i}return o}var Fo=o=>{let i=[];if(Ie(o))i=[...o];else if(ie(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Vm=o=>ie(o)?document.getElementById(o):o,Hg=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},Fm=()=>Hg(new Date);function _t(o,{keysToInclude:i,keysToExclude:e}){try{if(Ie(o))return`[${o.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ie(i)&&!Ie(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ie(o[n])?JSON.parse(_t(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Gs(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),_t(o,{keysToInclude:e})}function qs(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var gl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.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},Bo=o=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ie(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Na=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Js=o=>(Object.keys(o).forEach(i=>{z(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ie(o[i]))&&Js(o[i])}),o);function Ke(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function Da(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Ma(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function Oa(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===f.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function Ho(o,i){return o.width*o.height===i.width*i.height?1:gl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function Bm(o){return p(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function ya(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=ya(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=ya(o[t],i)}),e}return o}var $o=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))($o||{});function $g(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=L(O({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Gi(o,i,e,t){try{let r=$g(o,i,e,t),s=Aa(r);return Cm(s,e)}catch(r){return JSON.stringify(o)}}function ka(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function Pa(o){return(o&65535)>>>0}function Hm(o){return(o&4294901760)>>>0}function $m(o){let i=Wg(o);return i==null?void 0:i.busiBuff}function Wg(o){try{let i={},e=0;i.totalLength=ct(o,e),e+=4,i.version=ct(o,e),e+=4,i.encryption=ll(o,e),e+=1,i.uinType=ll(o,e),e+=1,i.uinLength=ct(o,e),e+=4,i.uin=i.uinLength>4?Po(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=Gg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=ct(o,e),e+=4,i.seqNo=ct(o,e),e+=4,i.retCode=ct(o,e),e+=4,i.retStrLength=ct(o,e),e+=4,i.retStr=i.retStrLength?Po(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=ct(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?Po(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=ct(o,e),e+=4,i.cookie=i.cookieLength?Po(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=ct(o,e),e+=4,i.busiBuffLength=ct(o,e),e+=4,i.busiBuff=i.busiBuffLength?Po(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Wm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Ca*Ra>>>0;for(let s=0;s<Ra;s++)t-=(e<<ml)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<ml)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Ca,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function Gg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Wm(r,i),n=s[0]&7,a=o.length-1-n-wo-Lo,c=new Uint8Array(a),l=0,u=t,m=o.slice(0,8);e=8;let h=1;h+=n;for(let g=1;g<=wo;)if(h<8)h++,g++;else if(h===8){let E=Tl(o,e,u,m,s,i);u=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,h=0}let _=a;for(;_>0;)if(h<8)c[l++]=s[h]^u[h],h++,_--;else if(h===8){let g=Tl(o,e,u,m,s,i);u=g.ivPreCrypt,m=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,h=0}for(let g=1;g<=Lo;)if(h<8)s[h]^u[h],h++,g++;else if(h===8){if(e>=o.length)break;let E=Tl(o,e,u,m,s,i);if(!E.success)break;u=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,h=0}return c}function Tl(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let u=0;u<8;u++)c[u]=r[u]^a[u];let l=Wm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Gm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function qi({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:$m(new Uint8Array(l))||(Gm?Gm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function El(o){return p(this,null,function*(){let i=U(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${U()-i}ms`),a}catch(t){return e}})}var qg=Object.prototype.hasOwnProperty;var Ii=o=>typeof o=="function",gt=o=>typeof o=="undefined";var wa=o=>typeof o=="boolean";var Sl=o=>o.isRemote;var Il=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);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 qm(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Il(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(qg.call(o,i))return!1;return!0}}return!1}var Jg=0,jg=1,Jm=2;function Xg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,m=-1,h=Jg,_=(g,E)=>p(this,null,function*(){let A=n||this;try{let k=yield o.apply(A,a);u>0&&s&&s.call(this,u),u=0,g(k)}catch(k){let re=()=>{clearTimeout(m),u=0,h=Jm,E(k)},P=()=>{h!==Jm&&u<(Ii(c)?c():c)?(u++,h=jg,Ii(t)&&t.call(this,u,re),m=window.setTimeout(()=>{m=-1,_(g,E)},Ii(l)?l(u):l)):(re(),Ii(r)&&r.call(this,k))};Ii(e)?e.call(this,{error:k,retry:P,reject:E,retryFuncArgs:a,retriedCount:u}):P()}});return new Promise(_)}}var Ai=Xg;var Er=class o{constructor(i){d(this,"_parentPath");d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=wa(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:gt(i.userId)?this.userId:i.userId,sdkAppId:gt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:gt(i.type)?this.type:i.type,isLocal:gt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:gt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,gt(this.userId)||qm(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 Ko={};Vi(Ko,{ANDROID_VERSION:()=>xa,CHROME_MAJOR_VERSION:()=>qe,CHROME_VERSION:()=>Ka,EDGE_VERSION:()=>Va,EDG_MAJOR_VERSION:()=>Cl,EDG_VERSION:()=>Fa,ELECTRON_MAJOR_VERSION:()=>Nl,FIREFOX_MAJOR_VERSION:()=>qo,FIREFOX_VERSION:()=>Ua,HUAWEI_VERSION:()=>za,IE_VERSION:()=>Kg,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>Tt,IPADQQB_VERSION:()=>ja,IS_ANDROID:()=>_e,IS_ANDROID_WEBVIEW:()=>rT,IS_ANY_SAFARI:()=>Ft,IS_CHROME:()=>Zo,IS_CHROME_OS:()=>Rl,IS_CHROMIUM_BASE:()=>$e,IS_DESKTOP_IOS_CHROME:()=>kl,IS_EDG:()=>Jo,IS_EDGE:()=>zr,IS_ELECTRON:()=>tT,IS_FIREFOX:()=>K,IS_HEADLESS_CHROME:()=>vl,IS_HONOR:()=>bl,IS_HUAWEI:()=>rn,IS_HUAWEIBROWSER:()=>tn,IS_IE:()=>Qm,IS_IE8:()=>Zg,IS_IOS:()=>ge,IS_IOS_13_OR_14:()=>Ol,IS_IOS_15_1:()=>Ml,IS_IOS_CHROME:()=>js,IS_IPAD:()=>Go,IS_IPADQQB:()=>Zs,IS_IPAD_PRO:()=>Al,IS_IPHONE:()=>Sr,IS_IPOD:()=>zm,IS_LINUX:()=>Ks,IS_LOCAL:()=>oi,IS_MAC:()=>ri,IS_MACQQB:()=>Ys,IS_MIBROWSER:()=>en,IS_MQQB:()=>Xo,IS_NATIVE_ANDROID:()=>Yg,IS_OLD_ANDROID:()=>Qg,IS_OPENHARMONY:()=>Qo,IS_OPPOBROWSER:()=>zo,IS_SAFARI:()=>Re,IS_SAFARI_15_1:()=>oT,IS_SAMSUNGBROWSER:()=>on,IS_SOGOU:()=>zs,IS_SOGOUM:()=>Xs,IS_TBS:()=>ii,IS_UCBROWSER:()=>yl,IS_VIVOBROWSER:()=>sn,IS_WECHAT:()=>ji,IS_WIN:()=>Qr,IS_WQQB:()=>Qs,IS_WX:()=>eT,IS_X5MQQB:()=>jo,IS_XWEB:()=>Ji,MACQQB_VERSION:()=>Ja,MI_VERSION:()=>Xa,MQQB_VERSION:()=>Wo,OPENHARMONY_VERSION:()=>iT,OPPO_VERSION:()=>Ya,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>Qa,SOGOUM_VERSION:()=>Ba,SOGOU_VERSION:()=>Ha,TBS_VERSION:()=>$a,UA_DATA_STRING:()=>ti,USER_AGENT:()=>Vt,VIVO_VERSION:()=>Za,WECHAT_VERSION:()=>Ga,WQQB_VERSION:()=>qa,XWEB_VERSION:()=>Wa,browserInfo:()=>Ci,getBrowserCoreNumber:()=>wl,getBrowserInfo:()=>Ym,getChromeMajorVersion:()=>Yo,getDeviceModel:()=>si,getDeviceModelFromUA:()=>ec,getGPUInfo:()=>Pl,getOSName:()=>tc,getOSNumber:()=>Zr,getOSString:()=>ni,getOSType:()=>sT,getTerminalType:()=>Ll,getUserAgentData:()=>Yr,isLocalStorageEnabled:()=>zi,isMobile:()=>an,isVersionLargerThan:()=>Dl,isVersionSmallerThan:()=>nn});var Vt=typeof navigator=="undefined"?"":navigator.userAgent,Z=o=>new RegExp(o,"i").test(Vt),we=o=>{if(Z(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Vt.match(i);if(e&&e[1])return e[1]}return""},La=o=>{if(Z(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Vt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},jm=/AppleWebKit\/([\d.]+)/i.exec(Vt),zg=jm?parseFloat(jm[1]):NaN,Go=Z("iPad"),Al=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Z("Macintosh"),Sr=Z("iPhone")&&!Go,zm=Z("iPod"),ge=Sr||Go||zm||Al,_e=Z("Android"),xa=function(){if(_e){let o=Vt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),Qg=_e&&Z("webkit")&&xa<2.3,Yg=_e&&xa<5&&zg<537,K=Z("Firefox"),Ua=we("Firefox"),qo=La("Firefox"),zr=Z("Edge"),Va=we("Edge"),Jo=Z("Edg"),Fa=we("Edg"),Cl=La("Edg"),Xs=Z("SogouMobileBrowser"),Ba=we("SogouMobileBrowser"),zs=Z("MetaSr\\s"),Ha=we("MetaSr\\s"),ii=Z("TBS"),$a=we("TBS"),Ji=Z("XWEB"),Wa=we("XWEB"),Zg=Z("MSIE\\s8\\.0"),Qm=Z("MSIE\\/\\d+"),Kg=function(){if(Qm){let o=/MSIE\s(\d+)\.\d/.exec(Vt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Vt)&&/rv:11.0/.test(Vt)&&(i=11),i}return NaN}(),ji=Z("(micromessenger|webbrowser)"),Ga=we("MicroMessenger"),jo=!ii&&Z("MQQBrowser")&&Z("COVC"),Xo=!ii&&Z("MQQBrowser")&&!Z("COVC"),Wo=Xo||jo?we("MQQBrowser"):"",Qs=!ii&&Z(" QQBrowser"),qa=we(" QQBrowser"),Ys=!ii&&Z("QQBrowserLite"),Ja=we("QQBrowserLite"),Zs=!ii&&Z("MQBHD"),ja=we("MQBHD"),Qr=Z("Windows"),ri=!ge&&Z("MAC OS X"),Ks=!_e&&Z("Linux"),Rl=Z("CrOS"),eT=Z("MicroMessenger"),yl=Z("UCBrowser"),tT=Z("Electron"),en=Z("MiuiBrowser"),Xa=we("MiuiBrowser"),tn=Z("HuaweiBrowser"),rn=Z("Huawei")||Z("HUAWEI"),bl=Z("Honor")||Z("HONOR"),za=we("HuaweiBrowser"),on=Z("SamsungBrowser"),Qa=we("SamsungBrowser"),zo=Z("HeyTapBrowser"),Ya=we("HeyTapBrowser"),sn=Z("VivoBrowser"),Za=we("VivoBrowser"),Qo=Z("OpenHarmony"),iT=we("OpenHarmony"),Yo=()=>La("Chrome"),js=Z("CriOS"),$e=Z("Chrome"),Zo=!zr&&!zs&&!Xs&&!ii&&!Ji&&!Jo&&!Qs&&!en&&!tn&&!on&&!zo&&!sn&&$e,vl=Z("HeadlessChrome"),qe=Yo(),Ka=we("Chrome"),Nl=La("Electron"),Re=!$e&&!Xo&&!jo&&!Ys&&!Zs&&Z("Safari"),Ft=Re||ge,Xi=we("Version"),rT=/Android.*(wv|.0.0.0)/.test(Vt),Tt=(()=>{if(Al)return Xi;if(ge){let o=Vt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function nn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function Dl(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(Tt.split(".")[0]),oT=Xi==="15.1",Ml=Tt==="15.1",Ol=(()=>{let o=Number(Tt.split(".")[0]);return o===14||o===13})(),kl=js&&Xi==="11.1.1",oi=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),Ci=Ym();function Ym(){let o=new Map([[K,["Firefox",Ua]],[Jo,["Edg",Fa]],[Zo,["Chrome",Ka]],[js,["ChiOS",we("CriOS")]],[Re&&!js,["Safari",Xi]],[ii,["TBS",$a]],[Ji,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",qa]],[Xo,["QQ(Mobile)",Wo]],[jo,["QQ(Mobile X5)",Wo]],[Ys,["QQ(Mac)",Ja]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[zo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Ba]],[zs,["Sogou",Ha]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var me=null;function an(){return me&&typeof me.mobile=="boolean"?me.mobile:_e||ge||Sr||Go||Qo}var ti="";function Yr(){return p(this,null,function*(){if(me)return me;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return me=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),me&&!ti&&(ti=`UAData: ${me.platform}/${me.platformVersion}`,me.architecture&&me.bitness&&(ti+=` ${me.architecture}/${me.bitness}`),me.mobile&&(ti+=" mobile"),me.model&&(ti+=` model: ${me.model.replace(/\s+/g,"/")}`),me.fullVersionList&&(ti+=` ${me.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),me}catch(o){return null}})}function Pl(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function si(){return(me==null?void 0:me.model)||ec()||""}function ec(){let o=/;\s*([^;)]+)\s+Build\//,i=Vt.match(o);return i!=null&&i[1]?i[1].trim():null}var Xm=new Map([[_e,"Android"],[ge,"iOS"],[Qr,"Windows"],[ri,"MacOS"],[Ks,"Linux"],[Rl,"ChromeOS"]]),tc=function(){return Xm.get(!0)?Xm.get(!0):me?me.platform:"unknown"};function Zr(){return Qr?1:_e?2:ri?3:ge?4:Ks?5:Rl?6:Qo?7:0}function wl(){return ji||Ji?4:$e?1:Re?2:K?3:0}var ni=()=>{let o=tc();return me!=null&&me.platformVersion?o+=`/${me.platformVersion}`:ge?o+=`/${Tt}`:_e&&(o+=`/${xa}`),o+=`/${Ci.name}/${Re&&!js?Ci.version:Ci.version.split(".")[0]}`,me!=null&&me.architecture&&(o+=`/${me.architecture}`),o};function Ll(){return _e?4:Sr?2:Go?3:ri?12:Qr?5:Ks?13:Qo?22:1}function sT(){return _e?"Android":Sr?"iPhone":Go?"iPad":ri?"Mac":Qr?"Windows":Ks?"Linux":"unknown"}var Zm=Ge(at(),1),nT=new Zm.default,S=nT;var mt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.LOCAL_AUDIO_STARTED="113",W.LOCAL_AUDIO_STOPPED="114",W.REMOTE_AUDIO_STARTED="115",W.REMOTE_AUDIO_STOPPED="116",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.AUDIO_CONTEXT_LONG_SUSPENDED="155",W.REMOTE_VIDEO_PLAY_START="156",W.REMOTE_VIDEO_PLAY_FINISH="157",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AUDIO_PROCESSOR_DEBUG="265",W.SSO_SWITCH="266",W.SEI_MESSAGE="267",W.SWITCH_ROOM_START="401",W.SWITCH_ROOM_SUCCESS="407",W.SWITCH_ROOM_FAILED="408",W))(mt||{});var C=mt;var xl=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ir=new xl;var aT="%cTRTC%c%s",cT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",dT="display: inline",ic=class ic{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Do&&!xs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(C.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Xt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(C.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(C.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(ie(t.userId)&&z(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:la(),sdkAppId:String(a),userId:n,version:He,log:c.map(h=>h.log).join(`
6
+ `)},u=JSON.stringify(l),m=Ir.enable?Gi(l,2002,a):u;yield this.uploadLogWithRetry(m,a,m instanceof Uint8Array,u),c.forEach(h=>h.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return Ai({retryFunction:()=>qi({url:Wi(e,mr.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(Ir.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(Fi()),`[${No(e)}] <${Xt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(Xt[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(ie(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};S.emit(C.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=Xt[i])==null?void 0:a.toLowerCase())||"info";ic.PRINT_LOG_TAG?console[n](aT,cT,dT,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){if(i.parent instanceof Er){let e=i,{parent:t}=e,r=aa(e,["parent"]),s=new Er(r);return s.bindParent(t),s}return new Er(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Xt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(ic,"PRINT_LOG_TAG",!(ge||_e||vl));var Ul=ic,R=new Ul;var lT=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},cn=lT;var Vl=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!zi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(zi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!zi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){R.warn(e)}}setItem(i,e){if(zi())try{let t={expiresIn:Date.now()+pa,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!zi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(zi())try{localStorage.clear()}catch(i){R.warn(i)}}},es=new Vl;var bi={};Vi(bi,{HTTPS_API:()=>PT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>du,IS_GET_CAPABILITIES_SUPPORTED:()=>cu,IS_GET_SETTINGS_SUPPORTED:()=>yi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>au,IS_INSERTABLE_STREAM_SUPPORTED:()=>hi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Sc,IS_RTC_RTP_SENDER_SUPPORTED:()=>gn,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>ss,IS_SEI_SUPPORTED:()=>En,IS_SPC_SUPPORTED:()=>os,basis:()=>xT,capabilityCheck:()=>hu,checkSystemRequirementsInternal:()=>_c,decodeSupportStatus:()=>fc,detectVideoCodecCapabilities:()=>mu,detectVideoDecoderCapabilities:()=>Mp,detectVideoEncoderCapabilities:()=>Dp,encodeSupportStatus:()=>su,getBrowserInfo:()=>bT,getDisplayResolution:()=>Ip,getH264ProfileLevelIds:()=>Op,isAddTransceiverSupported:()=>St,isBrowserSupported:()=>ou,isCanvasCaptureStreamAPISupported:()=>Rp,isCanvasSmallStreamSupported:()=>gc,isGetReceiversSupported:()=>oo,isGetSendersSupported:()=>Rr,isGetTransceiversSupported:()=>yr,isGetUserMediaSupported:()=>Ap,isMediaDevicesSupported:()=>pc,isMediaSessionSupported:()=>bp,isMediaStreamTrackGeneratorSupported:()=>vT,isMediaStreamTrackProcessorSupported:()=>fn,isReplaceTrackSupported:()=>nu,isRequestVideoFrameCallbackSupported:()=>Ki,isSIMDSupported:()=>uu,isScaleResolutionDownBySupported:()=>yp,isScreenCaptureApiAvailable:()=>_n,isSelectedCandidatePair:()=>Cr,isSetParametersSupported:()=>Tn,isSetSinkIdSupported:()=>MT,isSmallStreamSupported:()=>Tc,isStopTransceiverSupported:()=>LT,isTRTCSupported:()=>DT,isUnifiedPlanDefault:()=>wT,isUsedInHttpProtocol:()=>Zi,isWebAudioSupported:()=>Cp,isWebCodecSupported:()=>Ec,isWebCodecsSupported:()=>pn,isWebRTCSupported:()=>lu,isWebTransportSupported:()=>vp});var Yl={};Vi(Yl,{AUDIO_LEVEL_SCALE:()=>Dt,AlphaStitchingType:()=>hn,AudioCodecPipelineType:()=>ln,AudioDecoderDowngradeState:()=>$l,AudioPlayerMode:()=>Jl,AudioType:()=>ip,BASIC_TYPE:()=>Qi,BannedReason:()=>jl,CONNECTION_CLOSED_REASON:()=>Bl,CheckPermissionType:()=>Ql,ClientEvent:()=>Km,CodecType:()=>ap,ConnectionEvent:()=>ai,ConnectionState:()=>Nt,DECODE_FAILED_ERROR_CODE:()=>zl,DenoiserMode:()=>Xl,DeviceType:()=>cc,FacingMode:()=>sc,FrameWorkType:()=>rc,LeaveReason:()=>np,LocalTrackEvent:()=>Kr,MULTI_VIDEO_DATA_TYPE:()=>li,MediaType:()=>Ve,MediaTypeLabel:()=>uT,MonitorEventId:()=>dn,MutedFlag:()=>tp,NetworkQualityValue:()=>ql,PlayerState:()=>Ar,ReceiveMode:()=>sp,RemoteStreamType:()=>Et,RemoteTrackEvent:()=>eo,RoomEvent:()=>ci,SMALL_MODE:()=>un,SceneNumber:()=>Hl,StreamEvent:()=>ep,StreamType:()=>op,SubscribeMediaType:()=>Fl,TIMER_TYPE:()=>ui,TRACK_ACTION:()=>Gl,TRACK_KIND:()=>Wl,TrackEvent:()=>di,UserRole:()=>lt,UserRoleNumber:()=>to,VideoCodec:()=>Bt,VideoCodecPipelineType:()=>ac,VideoContentHint:()=>ts,VideoDecoderDowngradeState:()=>oc,VideoPlayerMode:()=>nc,VideoType:()=>rp});var rc=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(rc||{}),ai=(E=>(E.TRACK_ADDED="track-added",E.TRACK_UPDATED="track-updated",E.TRACK_SUBSCRIBED="track-subscribed",E.STREAM_ADDED="stream-added",E.STREAM_REMOVED="stream-removed",E.STREAM_UPDATED="stream-updated",E.STREAM_PUBLISHED="stream-published",E.STREAM_SUBSCRIBED="stream-subscribed",E.STREAM_UNSUBSCRIBED="stream-unsubscribed",E.STATE_CHANGED="state-changed",E.ERROR="error",E.CONNECTION_STATE_CHANGED="connection-state-changed",E.FIREWALL_RESTRICTION="firewall-restriction",E.SEI_MESSAGE="sei-message",E.CLOSED="closed",E))(ai||{}),Bl=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(Bl||{}),Km=(A=>(A.STREAM_ADDED="stream-added",A.STREAM_REMOVED="stream-removed",A.STREAM_UPDATED="stream-updated",A.STREAM_SUBSCRIBED="stream-subscribed",A.CONNECTION_STATE_CHANGED="connection-state-changed",A.PEER_JOIN="peer-join",A.PEER_LEAVE="peer-leave",A.MUTE_AUDIO="mute-audio",A.MUTE_VIDEO="mute-video",A.UNMUTE_AUDIO="unmute-audio",A.UNMUTE_VIDEO="unmute-video",A.CLIENT_BANNED="client-banned",A.NETWORK_QUALITY="network-quality",A.AUDIO_VOLUME="audio-volume",A.SEI_MESSAGE="sei-message",A.ERROR="error",A))(Km||{}),ep=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(ep||{}),Kr=(c=>(c.DEVICE_AUTO_RECOVERED="1",c.DEVICE_RECOVER_FAILED="5",c.DEVICE_CHANGED="2",c.ERROR="3",c.PUBLISH_STATE_CHANGED="4",c.ENCODE_FAILED="6",c.TRACK_ENDED="7",c.RENDER="render",c))(Kr||{}),Ar=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Ar||{}),ci=(b=>(b.PEER_JOIN="peer-join",b.PEER_LEAVE="peer-leave",b.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",b.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",b.BANNED="banned",b.NETWORK_QUALITY="network-quality",b.AUDIO_VOLUME="audio-volume",b.SEI_MESSAGE="sei-message",b.ERROR="error",b.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",b.REMOTE_PUBLISHED="remote-published",b.REMOTE_UNPUBLISHED="remote-unpublished",b.FIREWALL_RESTRICTION="firewall-restriction",b.HEARTBEAT_REPORT="heartbeat-report",b.CUSTOM_MESSAGE="custom-message",b.LAYER_DATA="layerData",b.FIRST_VIDEO_FRAME="first-video-frame",b.DUMP="dump",b.AUDIO_FRAME="audio-frame",b.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",b.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",b.NTP_TIME_UPDATED="ntp-time-updated",b))(ci||{}),di=(c=>(c.PLAYER_STATE_CHANGED="player-state-changed",c.MUTE="mute",c.UNMUTE="unmute",c.ERROR="error",c.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",c.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",c.FIRST_VIDEO_FRAME="first-video-frame",c.VIDEO_SIZE_CHANGED="video-size-changed",c))(di||{}),eo=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(eo||{}),tp=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(tp||{}),Hl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Hl||{}),to=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(to||{}),lt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(lt||{}),Nt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Nt||{}),$l=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))($l||{}),oc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(oc||{}),Wl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Wl||{}),Gl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Gl||{}),Ve=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(Ve||{}),uT={1:"audio",2:"auxVideo",4:"video"},ip=(i=>(i[i.opus=111]="opus",i))(ip||{}),rp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(rp||{}),op=(e=>(e.Big="big",e.Small="small",e))(op||{}),Et=(e=>(e.Main="main",e.Aux="auxiliary",e))(Et||{}),li=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(li||{}),dn=(w=>(w[w.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",w[w.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",w[w.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",w[w.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",w[w.MUTE_AUDIO=32772]="MUTE_AUDIO",w[w.MUTE_VIDEO=32773]="MUTE_VIDEO",w[w.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",w[w.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",w[w.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",w[w.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",w[w.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",w[w.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",w[w.SWITCH_CAMERA=32780]="SWITCH_CAMERA",w[w.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",w[w.REPLACE_VIDEO=32782]="REPLACE_VIDEO",w[w.REPLACE_AUDIO=32783]="REPLACE_AUDIO",w[w.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",w[w.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",w[w.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",w[w.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",w[w.JOIN=32788]="JOIN",w[w.LEAVE=32789]="LEAVE",w[w.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",w[w.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",w[w.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",w[w.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",w[w.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",w[w.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",w[w.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",w[w.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",w[w.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",w[w.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",w[w.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",w[w.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",w[w.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",w[w.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",w[w.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",w[w.PUBLISH_AUX=32805]="PUBLISH_AUX",w[w.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",w[w.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",w[w.VIDEO_ENCODER=4004]="VIDEO_ENCODER",w[w.VIDEO_DECODER=4005]="VIDEO_DECODER",w))(dn||{}),ql=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(ql||{}),sp=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(sp||{}),sc=(e=>(e.user="user",e.environment="environment",e))(sc||{}),nc=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(nc||{}),Jl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Jl||{}),jl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(jl||{}),np=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(np||{}),Dt=1e8,Xl=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Xl||{}),Fl=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Qi||{}),Bt=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Bt||{}),ac=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ac||{}),ln=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ln||{}),ap=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(ap||{}),zl=(h=>(h[h.SUCCESS=0]="SUCCESS",h[h.FAILED=1]="FAILED",h[h.WEBCODEC_INIT=2]="WEBCODEC_INIT",h[h.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",h[h.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",h[h.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",h[h.WASM_INIT=6]="WASM_INIT",h[h.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",h[h.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",h[h.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",h[h.TEST=10]="TEST",h[h.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",h))(zl||{}),ts=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(ts||{}),ui=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(ui||{}),un=(e=>(e.CANVAS="canvas",e.API="api",e))(un||{}),Ql=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(Ql||{}),cc=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(cc||{}),hn=(t=>(t[t.none=0]="none",t[t.horizontal=1]="horizontal",t[t.vertical=2]="vertical",t))(hn||{});var F={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"},Je={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.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(o){return`exchange sdp failed ${o.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(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' 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:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.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(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} 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:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},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(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.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(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' 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(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||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(o){return`'${o}' 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:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.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(o){return`${o}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(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"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:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!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:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.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:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var cp=(o,i)=>i?`${ft}/${o}/${i}`:`${ft}/${o}/index.html`;var hT=()=>{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 o=localStorage==null?void 0:localStorage.getItem(Xd);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.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 H(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";le(Je[i])?s=Je[i](e):ie(Je[i])&&(s=Je[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=hT();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(le(l[i])?a=l[i](e):ie(l[i])&&(a=l[i]));let u=s;return Yt()&&(c&&c[i]&&(le(c[i])?n=c[i](e):ie(c[i])&&(n=c[i])),n&&(r?u=`${n}
7
7
  \u8BF7\u67E5\u770B\u6587\u6863: ${cp("zh-cn",a)}
8
8
 
9
9
  `:u=`${n}
10
10
 
11
11
  `,u+=s)),r&&(u+=`
12
12
  Refer to: ${cp("en",a)}
13
- `),u}var iu=Je(_p(),1);var IT=1,AT=0,lc=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",R.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===p.AUDIO?501700:511700,cost:t})}),S.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===p.AUDIO?501700:511700,error:t})}),S.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(i,e){let t={msg_sdk_basic_info:{uint32_sdk_version:Na(this.version||$e),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([r,s])=>({uint32_key:r,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([r,s])=>({uint32_key:r,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:i,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),t}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 s;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((s=this.distributionMap)==null?void 0:s.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1,max:s=5e3}){var c;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;e>s&&(e=s),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(i))||new Map,a=0;if(Q(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:IT,useUV:!1}),e)){let s=+String(i).slice(-3);s<800&&s>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;e&&(Q(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:AT,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},uc=(y=>(y[y.enterRoom=500700]="enterRoom",y[y.exitRoom=500701]="exitRoom",y[y.switchRole=500702]="switchRole",y[y.destroy=500703]="destroy",y[y.startLocalAudio=500704]="startLocalAudio",y[y.updateLocalAudio=500705]="updateLocalAudio",y[y.stopLocalAudio=500706]="stopLocalAudio",y[y.startLocalVideo=500707]="startLocalVideo",y[y.updateLocalVideo=500708]="updateLocalVideo",y[y.stopLocalVideo=500709]="stopLocalVideo",y[y.startScreenShare=500710]="startScreenShare",y[y.updateScreenShare=500711]="updateScreenShare",y[y.stopScreenShare=500712]="stopScreenShare",y[y.startRemoteVideo=500713]="startRemoteVideo",y[y.updateRemoteVideo=500714]="updateRemoteVideo",y[y.stopRemoteVideo=500715]="stopRemoteVideo",y[y.muteRemoteAudio=500716]="muteRemoteAudio",y[y.setRemoteAudioVolume=500717]="setRemoteAudioVolume",y[y.use=500718]="use",y[y.switchRoom=500719]="switchRoom",y[y.sendSEIMessage=5e5]="sendSEIMessage",y[y.sendCustomMessage=500001]="sendCustomMessage",y))(uc||{}),Kl=(m=>(m[m.AudioMixer=550700]="AudioMixer",m[m.AIDenoiser=551700]="AIDenoiser",m[m.VirtualBackground=570700]="VirtualBackground",m[m.Beauty=571700]="Beauty",m[m.Watermark=572700]="Watermark",m[m.BasicBeauty=574700]="BasicBeauty",m[m.CDNStreaming=590700]="CDNStreaming",m[m.DeviceDetector=591700]="DeviceDetector",m[m.Debug=592700]="Debug",m[m.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",m[m.VideoMixer=594700]="VideoMixer",m[m.AudioProcessor=595700]="AudioProcessor",m))(Kl||{}),eu=(m=>(m[m.AudioMixer=550701]="AudioMixer",m[m.AIDenoiser=551701]="AIDenoiser",m[m.VirtualBackground=570701]="VirtualBackground",m[m.Beauty=571701]="Beauty",m[m.Watermark=572701]="Watermark",m[m.BasicBeauty=574701]="BasicBeauty",m[m.CDNStreaming=590701]="CDNStreaming",m[m.DeviceDetector=591701]="DeviceDetector",m[m.Debug=592701]="Debug",m[m.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",m[m.VideoMixer=594701]="VideoMixer",m[m.AudioProcessor=595701]="AudioProcessor",m))(eu||{}),tu=(m=>(m[m.AudioMixer=550702]="AudioMixer",m[m.AIDenoiser=551702]="AIDenoiser",m[m.VirtualBackground=570702]="VirtualBackground",m[m.Beauty=571702]="Beauty",m[m.Watermark=572702]="Watermark",m[m.BasicBeauty=574702]="BasicBeauty",m[m.CDNStreaming=590702]="CDNStreaming",m[m.DeviceDetector=591702]="DeviceDetector",m[m.Debug=592702]="Debug",m[m.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",m[m.VideoMixer=594702]="VideoMixer",m[m.AudioProcessor=595702]="AudioProcessor",m))(tu||{});var os=(w=>(w[w.DECODER_TYPE=514700]="DECODER_TYPE",w[w.DECODER_HW_SW=514701]="DECODER_HW_SW",w[w.DECODE_RESULT=514702]="DECODE_RESULT",w[w.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",w[w.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",w[w.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",w[w.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",w[w.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",w[w.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",w[w.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",w[w.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",w[w.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",w[w.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",w[w.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",w[w.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",w[w.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",w[w.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",w[w.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",w[w.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",w))(os||{});var CT=new lc(!0),ro=new lc(!1);var v=CT;var ee={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},RT=new Map([[te,["Firefox",Ua]],[jo,["Edg",Ba]],[Ko,["Chrome",Ka]],[Pe,["Safari",Xi]],[ri,["TBS",$a]],[qi,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",Ja]],[zo,["QQ(Mobile)",Go]],[Xo,["QQ(Mobile X5)",Go]],[Ys,["QQ(Mac)",qa]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[Qo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Fa]],[zs,["Sogou",Ha]]]);function yT(){let o=RT.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var ou=function(){return!(yl||zr||jo&&Cl<80||te&&qo<56)},pn=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},pc=function(){if(!navigator.mediaDevices)return Zi()||R.error(je.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},gp=!1;function Zi(){return location.protocol==="http:"&&!si?(gp||R.error(H({key:B.NOT_SUPPORTED_HTTP})),gp=!0,!0):!1}var fn=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},bT=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},su=function(){return f(this,null,function*(){var r,s,n;if(ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ee.detail.isH264EncodeSupported,isVp8EncodeSupported:ee.detail.isVp8EncodeSupported,isH265EncodeSupported:ee.detail.isH265EncodeSupported};let o,i=!1,e=!1,t=!1;try{let a=new RTCPeerConnection,c=document.createElement(p.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),o=yield a.createOffer(),i=((r=o.sdp)==null?void 0:r.toLowerCase().indexOf("h264"))!==-1,e=((s=o.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,t=((n=o.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:i,isVp8EncodeSupported:e,isH265EncodeSupported:t}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},fc=function(){return f(this,null,function*(){var t;if(ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ee.detail.isH264DecodeSupported,isVp8DecodeSupported:ee.detail.isVp8DecodeSupported,isH265DecodeSupported:ee.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;St()?(r.addTransceiver(p.VIDEO,{direction:"recvonly"}),o=yield r.createOffer()):o=yield r.createOffer({offerToReceiveVideo:!0}),o.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),o.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((t=o.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return r.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function vT(){return f(this,null,function*(){let[o,i]=yield Promise.all([su(),fc()]);return{encode:{h264:o.isH264EncodeSupported,vp8:o.isVp8EncodeSupported,h265:o.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}})}var _c=Da(o=>f(void 0,null,function*(){let i=Date.now(),e=lu(),t=pc(),r=pn();if(ee.detail.isWebRTCSupported=e,ee.detail.isMediaDevicesSupported=t,ee.detail.isWebCodecsSupported=r,ee.detail.isScreenShareSupported=_n(),ee.detail.isSmallStreamSupported=Tc(),o===37)return Object.assign(ee.detail,yield MT()),ee.detail.isBrowserSupported=r,ee.result=t&&r,ee.result||R.error(`${navigator.userAgent} ${Gs(ee.detail,!1)}`),Tp(o),v.addNumber({key:523800,value:Date.now()-i}),ee;if(ee.result&&ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported&&ee.detail.isH265EncodeSupported&&ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported&&ee.detail.isH265DecodeSupported)return ee;let s=ou(),{encode:n,decode:a}=yield vT(),{h264:c,vp8:l}=n,{h264:u}=a,{h265:h}=n,{vp8:m,h265:_}=a;if(!c||!l){let g=yield su();R.warn(`detect encode again h264:${c} vp8:${l} result: ${JSON.stringify(g)}`),c=g.isH264EncodeSupported,l=g.isVp8EncodeSupported}if(c&&u&&_e&&We&&!qi&&!ri&&!(Qo&&qe===115)){let{encode:g,decode:E}=yield OT();c=g,u=E}return ee.result=s&&e&&t&&(c||l)&&(u||m),ee.detail.isBrowserSupported=s,ee.detail.isWebRTCSupported=e,ee.detail.isH264EncodeSupported=c,ee.detail.isVp8EncodeSupported=l,ee.detail.isH265EncodeSupported=h,ee.detail.isH264DecodeSupported=u,ee.detail.isVp8DecodeSupported=m,ee.detail.isH265DecodeSupported=_,ee.result||R.error(`${navigator.userAgent} ${Gs(ee.detail,!1)}`),Tp(),v.addNumber({key:523800,value:Date.now()-i}),ee})),NT=function(){return ee.result},_n=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},DT=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,hc=null;function OT(){return f(this,null,function*(){return hc||(hc=new Promise(o=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=640,t.height=480;let s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),u.close(),c.getTracks().forEach(E=>E.stop())},a=setTimeout(()=>{e(),o(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",E=>u.addIceCandidate(E.candidate)),u.addEventListener("icecandidate",E=>l.addIceCandidate(E.candidate)),l.addTrack(c.getVideoTracks()[0],c);let h=yield l.createOffer();yield l.setLocalDescription(h),yield u.setRemoteDescription(h);let m=yield u.createAnswer(),_=iu.default.parse(m.sdp),g=_.media[0].rtp.findIndex(E=>E.codec==="H264");_.media[0].rtp=[_.media[0].rtp[g]],_.media[0].fmtp=_.media[0].fmtp.filter(E=>E.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(E=>E.payload===_.media[0].rtp[0].payload)),m.sdp=iu.default.write(_),yield u.setLocalDescription(m),yield l.setRemoteDescription(m),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[E,C]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||E.forEach(k=>{k.type==="outbound-rtp"&&k.mediaType===p.VIDEO&&k.bytesSent>0&&(i.encode=!0)}),i.decode||C.forEach(k=>{k.type==="inbound-rtp"&&k.mediaType===p.VIDEO&&k.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),R.warn("detectH264Supported failed",t),o({encode:!0,decode:!0})}})).then(o=>(o.encode||(o.decode=!0),(!o.encode||!o.decode)&&R.warn(`detectH264Supported encode: ${o.encode} decode: ${o.decode} ${ii}`),o)),hc)})}var mc=null;function MT(){return f(this,null,function*(){return mc||(mc=new Promise(o=>f(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!pn()){o(i);return}let e=null,t=null,r=null,s=()=>{r&&clearTimeout(r),e=null,t=null};try{e=document.createElement("canvas"),t=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!t||!e||(t.fillStyle=`hsl(${n%360}, 50%, 50%)`,t.fillRect(0,0,e.width,e.height),t.fillStyle="white",t.font="20px Arial",t.fillText(`Frame ${n}`,10,30),n++)};r=setTimeout(()=>{s(),o(i)},5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map(u=>f(this,null,function*(){let h={type:u.type,encodeSupported:!1,decodeSupported:!1},m;try{m=yield new Promise((_,g)=>f(this,null,function*(){try{let E=new VideoEncoder({output:k=>{_(k),h.encodeSupported=!0},error:g});E.configure(u.encodeConfig),a();let C=new VideoFrame(e,{timestamp:0});E.encode(C,{keyFrame:!0}),C.close(),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){return R.warn(`${u.type} encoder error:`,_),h}try{yield new Promise((_,g)=>f(this,null,function*(){try{let E=new VideoDecoder({output:C=>{h.decodeSupported=!0,_(0),C.close()},error:g});E.configure(u.decodeConfig),E.decode(m),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){R.warn(`${u.type} decoder error:`,_)}return h})))).forEach(u=>{u.type==="h264"?(i.isH264EncodeSupported=u.encodeSupported,i.isH264DecodeSupported=u.decodeSupported):u.type==="vp8"&&(i.isVp8EncodeSupported=u.encodeSupported,i.isVp8DecodeSupported=u.decodeSupported)}),s(),o(i)}catch(n){s(),R.warn("detectWebCodecsSupported failed:",n),o(i)}})),mc)})}var kT=(o,i,e)=>{location.protocol==="http:"&&!si&&(o[i]=()=>{throw new D({code:I.INVALID_OPERATION,message:je.NOT_SUPPORTED_HTTP})})},Cr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(me(o.selected)&&!o.selected):!1};function Ip(){let o="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";o+=`${i} * ${e}`}return o}function Ap(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Cp(){let o={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){o.isSupported=!0;break}return o.isSupported}function Rp(){return"captureStream"in HTMLCanvasElement.prototype}function gc(){return ji||Te||qe&&qe<63?!1:!!(ou()&&Rp())}function yp(){return!(qe<74||zr||et<11||qo<46)}function Tc(){return gc()||yp()}var PT=function(){if(T(window.RTCRtpTransceiver)||!St()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:gr}),o.addTransceiver(p.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function oo(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Rr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function yr(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function St(){return et===11&&!kl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var ss=!(!St()||We&&qe<86);function wT(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var gn="RTCRtpSender"in window;function nu(){return gn&&"replaceTrack"in window.RTCRtpSender.prototype}function Tn(){return gn&&"setParameters"in window.RTCRtpSender.prototype&&Rr()}var au="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,bi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,cu=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,du=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,mi=gn&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Zo()>=86,ns="RTCRtpScriptTransform"in window,En=gn&&(mi||ns),lu=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Ec(){let o={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(o.AudioDecoder=!0),T(window.AudioEncoder)||(o.AudioEncoder=!0),T(window.VideoDecoder)||(o.VideoDecoder=!0),T(window.VideoEncoder)||(o.VideoEncoder=!0),T(window.ImageDecoder)||(o.ImageDecoder=!0),o}function bp(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function vp(){return!T(window.WebTransport)}function uu(){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 LT(){let o={browser:`${Ri.name}/${Ri.version}`,os:tc(),displayResolution:Ip(),isScreenShareSupported:_n(),isWebRTCSupported:lu(),isGetUserMediaSupported:Ap(),isWebAudioSupported:Cp(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ec(),isMediaSessionSupported:bp(),isWebTransportSupported:vp()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var Np="checkResult";function Tp(o=30){ts.setItem(Np+o,{ua:navigator.userAgent,checkResult:ee})}function hu(o){Zi();let i=ts.getItem(Np+o);i&&i.ua===navigator.userAgent&&i.checkResult&&xT(i.checkResult.detail,ee.detail)&&(ee=i.checkResult),_c(o)}function xT(o,i){return yt(o)?Object.keys(i).every(e=>e in o):!1}function Ki(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Sc="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function Ep(o){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[o]}var Sp=!1;function mu(){return f(this,null,function*(){var o;try{if(Sp||!((o=navigator==null?void 0:navigator.mediaCapabilities)!=null&&o.encodingInfo))return;let i=Zr(),e=wl();if(i===0||e===0)return;Sp=!0;let t=["H264","VP8","VP9","AV1","H265"],[r,s]=yield Promise.all([Dp(t),Op(t)]);r&&Object.keys(r).forEach(c=>{let l=Ep(c.toLowerCase());v.addEnum({key:513707,value:+`${l}${+r[c].supported}${+r[c].powerEfficient}${i}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(c=>{let l=Ep(c.toLowerCase());v.addEnum({key:514713,value:+`${l}${+s[c].supported}${+s[c].powerEfficient}${i}${e}`,useUV:!1})});let{sender:n,receiver:a}=Mp();v.addEnum({key:513708,value:+`${i}${e}${+n.high}`,useUV:!1}),v.addEnum({key:513709,value:+`${i}${e}${+n.main}`,useUV:!1}),v.addEnum({key:514714,value:+`${i}${e}${+a.high}`,useUV:!1}),v.addEnum({key:514715,value:+`${i}${e}${+a.main}`,useUV:!1})}catch(i){R.info("detectVideoCodecCapabilities failed",i)}})}function Dp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Op(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Mp(){let o={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.sender.base=!0;break;case"4d":o.sender.main=!0;break;case"64":o.sender.high=!0;break}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.receiver.base=!0;break;case"4d":o.receiver.main=!0;break;case"64":o.receiver.high=!0;break}}})}}catch(i){R.warn("get H264 profile levelId failed",i)}return o}var Pp=Je(at(),1);var kp=Symbol("instance"),OC=Symbol("abortCtrl"),Ic=Symbol("cacheResult"),Sn=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Cn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},In=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function UT(o){return typeof o=="object"&&o&&"then"in o}var An=new Map;function ye(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let c=An.get(t)||[];An.has(t)||An.set(t,c),c.push({from:o,to:i,action:n})}let a=s.value;s.value=function(...c){let l=this;if(e.context&&(l=q.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[Ic]:Promise.resolve(l[Ic]);l.state instanceof Sn&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(o)?o.length==0?l.state instanceof Sn&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(u=new In(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(u=new In(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let h=C=>{if(e.fail&&e.fail.call(this,C),e.sync){if(e.ignoreError)return C;throw C}else return e.ignoreError?Promise.resolve(C):Promise.reject(C)};if(u)return h(u);let m=l.state,_=new Sn(m,i,n);Cn.call(l,_);let g=C=>{var k;return l[Ic]=C,_.aborted||(Cn.call(l,i),(k=e.success)===null||k===void 0||k.call(this,l[Ic])),C},E=C=>(Cn.call(l,m,C),h(C));try{let C=a.apply(this,c);return UT(C)?C.then(g).catch(E):e.sync?g(C):Promise.resolve(g(C))}catch(C){return E(new In(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${C}`,C instanceof Error?C:new Error(String(C))))}}}}var VT=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 Cn(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit(q.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var q=class o extends Pp.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=o.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[kp];r?this.name=r.name+"-"+r.count++:t[kp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=An.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);An.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:h})=>{typeof l=="string"?r.push({from:l,to:u,action:h}):l.length?l.forEach(m=>{r.push({from:m,to:u,action:h})}):s.push({to:u,action:h})}),r.forEach(({from:l,to:u,action:h})=>{n.add(l),n.add(u),n.add(h+"ing"),t.add(`${l} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${u} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${l} : ${h} \u{1F534}`)}),s.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(h=>{h!==l&&t.add(`${h} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=o.instances.get(i),e||o.instances.set(i,e=new o(i,void 0,Object.create(o.prototype)))):(e=o.instances2.get(i),e||o.instances2.set(i,e=new o(i.constructor.name,void 0,Object.create(o.prototype)))),e}static getState(i){var e;return(e=o.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){VT(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Cn.call(this,i)}};q.STATECHANGED="stateChanged";q.UPDATEAFSM="updateAFSM";q.INIT="[*]";q.ON="on";q.OFF="off";q.instances=new Map;q.instances2=new WeakMap;var fu=typeof window!="undefined",wp=fu&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},BT=fu&&window.cancelIdleCallback||function(o){clearTimeout(o)},Lp=fu&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Be=class Be{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=M({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=M({delay:1e4,count:0},t):i==="raf"?t=M({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=M({delay:2e3,count:0,backgroundTask:!0},t);let r=L(M({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Be.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Be.sharedWorker||(Be.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
13
+ `),u}var iu=Ge(_p(),1);var AT=1,CT=0,lc=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",R.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===f.AUDIO?501700:511700,cost:t})}),S.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===f.AUDIO?501700:511700,error:t})}),S.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(i,e){let t={msg_sdk_basic_info:{uint32_sdk_version:Na(this.version||He),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([r,s])=>({uint32_key:r,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([r,s])=>({uint32_key:r,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:i,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),t}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 s;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((s=this.distributionMap)==null?void 0:s.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1,max:s=5e3}){var c;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;e>s&&(e=s),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(i))||new Map,a=0;if(z(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:AT,useUV:!1}),e)){let s=+String(i).slice(-3);s<800&&s>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;e&&(z(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:CT,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},uc=(b=>(b[b.enterRoom=500700]="enterRoom",b[b.exitRoom=500701]="exitRoom",b[b.switchRole=500702]="switchRole",b[b.destroy=500703]="destroy",b[b.startLocalAudio=500704]="startLocalAudio",b[b.updateLocalAudio=500705]="updateLocalAudio",b[b.stopLocalAudio=500706]="stopLocalAudio",b[b.startLocalVideo=500707]="startLocalVideo",b[b.updateLocalVideo=500708]="updateLocalVideo",b[b.stopLocalVideo=500709]="stopLocalVideo",b[b.startScreenShare=500710]="startScreenShare",b[b.updateScreenShare=500711]="updateScreenShare",b[b.stopScreenShare=500712]="stopScreenShare",b[b.startRemoteVideo=500713]="startRemoteVideo",b[b.updateRemoteVideo=500714]="updateRemoteVideo",b[b.stopRemoteVideo=500715]="stopRemoteVideo",b[b.muteRemoteAudio=500716]="muteRemoteAudio",b[b.setRemoteAudioVolume=500717]="setRemoteAudioVolume",b[b.use=500718]="use",b[b.switchRoom=500719]="switchRoom",b[b.sendSEIMessage=5e5]="sendSEIMessage",b[b.sendCustomMessage=500001]="sendCustomMessage",b))(uc||{}),Kl=(h=>(h[h.AudioMixer=550700]="AudioMixer",h[h.AIDenoiser=551700]="AIDenoiser",h[h.VirtualBackground=570700]="VirtualBackground",h[h.Beauty=571700]="Beauty",h[h.Watermark=572700]="Watermark",h[h.BasicBeauty=574700]="BasicBeauty",h[h.CDNStreaming=590700]="CDNStreaming",h[h.DeviceDetector=591700]="DeviceDetector",h[h.Debug=592700]="Debug",h[h.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",h[h.VideoMixer=594700]="VideoMixer",h[h.AudioProcessor=595700]="AudioProcessor",h))(Kl||{}),eu=(h=>(h[h.AudioMixer=550701]="AudioMixer",h[h.AIDenoiser=551701]="AIDenoiser",h[h.VirtualBackground=570701]="VirtualBackground",h[h.Beauty=571701]="Beauty",h[h.Watermark=572701]="Watermark",h[h.BasicBeauty=574701]="BasicBeauty",h[h.CDNStreaming=590701]="CDNStreaming",h[h.DeviceDetector=591701]="DeviceDetector",h[h.Debug=592701]="Debug",h[h.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",h[h.VideoMixer=594701]="VideoMixer",h[h.AudioProcessor=595701]="AudioProcessor",h))(eu||{}),tu=(h=>(h[h.AudioMixer=550702]="AudioMixer",h[h.AIDenoiser=551702]="AIDenoiser",h[h.VirtualBackground=570702]="VirtualBackground",h[h.Beauty=571702]="Beauty",h[h.Watermark=572702]="Watermark",h[h.BasicBeauty=574702]="BasicBeauty",h[h.CDNStreaming=590702]="CDNStreaming",h[h.DeviceDetector=591702]="DeviceDetector",h[h.Debug=592702]="Debug",h[h.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",h[h.VideoMixer=594702]="VideoMixer",h[h.AudioProcessor=595702]="AudioProcessor",h))(tu||{});var rs=(P=>(P[P.DECODER_TYPE=514700]="DECODER_TYPE",P[P.DECODER_HW_SW=514701]="DECODER_HW_SW",P[P.DECODE_RESULT=514702]="DECODE_RESULT",P[P.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",P[P.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",P[P.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",P[P.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",P[P.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",P[P.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",P[P.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",P[P.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",P[P.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",P[P.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",P[P.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",P[P.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",P[P.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",P[P.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",P[P.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",P[P.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",P))(rs||{});var RT=new lc(!0),ro=new lc(!1);var v=RT;var ee={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},yT=new Map([[K,["Firefox",Ua]],[Jo,["Edg",Fa]],[Zo,["Chrome",Ka]],[Re,["Safari",Xi]],[ii,["TBS",$a]],[Ji,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",qa]],[Xo,["QQ(Mobile)",Wo]],[jo,["QQ(Mobile X5)",Wo]],[Ys,["QQ(Mac)",Ja]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[zo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Ba]],[zs,["Sogou",Ha]]]);function bT(){let o=yT.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var ou=function(){return!(yl||zr||Jo&&Cl<80||K&&qo<56)},pn=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},pc=function(){if(!navigator.mediaDevices)return Zi()||R.error(Je.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},gp=!1;function Zi(){return location.protocol==="http:"&&!oi?(gp||R.error(H({key:F.NOT_SUPPORTED_HTTP})),gp=!0,!0):!1}var fn=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},vT=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},su=function(){return p(this,null,function*(){var r,s,n;if(ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ee.detail.isH264EncodeSupported,isVp8EncodeSupported:ee.detail.isVp8EncodeSupported,isH265EncodeSupported:ee.detail.isH265EncodeSupported};let o,i=!1,e=!1,t=!1;try{let a=new RTCPeerConnection,c=document.createElement(f.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),o=yield a.createOffer(),i=((r=o.sdp)==null?void 0:r.toLowerCase().indexOf("h264"))!==-1,e=((s=o.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,t=((n=o.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:i,isVp8EncodeSupported:e,isH265EncodeSupported:t}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},fc=function(){return p(this,null,function*(){var t;if(ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ee.detail.isH264DecodeSupported,isVp8DecodeSupported:ee.detail.isVp8DecodeSupported,isH265DecodeSupported:ee.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;St()?(r.addTransceiver(f.VIDEO,{direction:"recvonly"}),o=yield r.createOffer()):o=yield r.createOffer({offerToReceiveVideo:!0}),o.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),o.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((t=o.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return r.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function NT(){return p(this,null,function*(){let[o,i]=yield Promise.all([su(),fc()]);return{encode:{h264:o.isH264EncodeSupported,vp8:o.isVp8EncodeSupported,h265:o.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}})}var _c=Da(o=>p(void 0,null,function*(){let i=Date.now(),e=lu(),t=pc(),r=pn();if(ee.detail.isWebRTCSupported=e,ee.detail.isMediaDevicesSupported=t,ee.detail.isWebCodecsSupported=r,ee.detail.isScreenShareSupported=_n(),ee.detail.isSmallStreamSupported=Tc(),o===37)return Object.assign(ee.detail,yield kT()),ee.detail.isBrowserSupported=r,ee.result=t&&r,ee.result||R.error(`${navigator.userAgent} ${Gs(ee.detail,!1)}`),Tp(o),v.addNumber({key:523800,value:Date.now()-i}),ee;if(ee.result&&ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported&&ee.detail.isH265EncodeSupported&&ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported&&ee.detail.isH265DecodeSupported)return ee;let s=ou(),{encode:n,decode:a}=yield NT(),{h264:c,vp8:l}=n,{h264:u}=a,{h265:m}=n,{vp8:h,h265:_}=a;if(!c||!l){let g=yield su();R.warn(`detect encode again h264:${c} vp8:${l} result: ${JSON.stringify(g)}`),c=g.isH264EncodeSupported,l=g.isVp8EncodeSupported}if(c&&u&&_e&&$e&&!Ji&&!ii&&!(zo&&qe===115)){let{encode:g,decode:E}=yield OT();c=g,u=E}return ee.result=s&&e&&t&&(c||l)&&(u||h),ee.detail.isBrowserSupported=s,ee.detail.isWebRTCSupported=e,ee.detail.isH264EncodeSupported=c,ee.detail.isVp8EncodeSupported=l,ee.detail.isH265EncodeSupported=m,ee.detail.isH264DecodeSupported=u,ee.detail.isVp8DecodeSupported=h,ee.detail.isH265DecodeSupported=_,ee.result||R.error(`${navigator.userAgent} ${Gs(ee.detail,!1)}`),Tp(),v.addNumber({key:523800,value:Date.now()-i}),ee})),DT=function(){return ee.result},_n=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},MT=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,hc=null;function OT(){return p(this,null,function*(){return hc||(hc=new Promise(o=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=640,t.height=480;let s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),u.close(),c.getTracks().forEach(E=>E.stop())},a=setTimeout(()=>{e(),o(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",E=>u.addIceCandidate(E.candidate)),u.addEventListener("icecandidate",E=>l.addIceCandidate(E.candidate)),l.addTrack(c.getVideoTracks()[0],c);let m=yield l.createOffer();yield l.setLocalDescription(m),yield u.setRemoteDescription(m);let h=yield u.createAnswer(),_=iu.default.parse(h.sdp),g=_.media[0].rtp.findIndex(E=>E.codec==="H264");_.media[0].rtp=[_.media[0].rtp[g]],_.media[0].fmtp=_.media[0].fmtp.filter(E=>E.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(E=>E.payload===_.media[0].rtp[0].payload)),h.sdp=iu.default.write(_),yield u.setLocalDescription(h),yield l.setRemoteDescription(h),n=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[E,A]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||E.forEach(k=>{k.type==="outbound-rtp"&&k.mediaType===f.VIDEO&&k.bytesSent>0&&(i.encode=!0)}),i.decode||A.forEach(k=>{k.type==="inbound-rtp"&&k.mediaType===f.VIDEO&&k.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),R.warn("detectH264Supported failed",t),o({encode:!0,decode:!0})}})).then(o=>(o.encode||(o.decode=!0),(!o.encode||!o.decode)&&R.warn(`detectH264Supported encode: ${o.encode} decode: ${o.decode} ${ti}`),o)),hc)})}var mc=null;function kT(){return p(this,null,function*(){return mc||(mc=new Promise(o=>p(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!pn()){o(i);return}let e=null,t=null,r=null,s=()=>{r&&clearTimeout(r),e=null,t=null};try{e=document.createElement("canvas"),t=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!t||!e||(t.fillStyle=`hsl(${n%360}, 50%, 50%)`,t.fillRect(0,0,e.width,e.height),t.fillStyle="white",t.font="20px Arial",t.fillText(`Frame ${n}`,10,30),n++)};r=setTimeout(()=>{s(),o(i)},5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map(u=>p(this,null,function*(){let m={type:u.type,encodeSupported:!1,decodeSupported:!1},h;try{h=yield new Promise((_,g)=>p(this,null,function*(){try{let E=new VideoEncoder({output:k=>{_(k),m.encodeSupported=!0},error:g});E.configure(u.encodeConfig),a();let A=new VideoFrame(e,{timestamp:0});E.encode(A,{keyFrame:!0}),A.close(),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){return R.warn(`${u.type} encoder error:`,_),m}try{yield new Promise((_,g)=>p(this,null,function*(){try{let E=new VideoDecoder({output:A=>{m.decodeSupported=!0,_(0),A.close()},error:g});E.configure(u.decodeConfig),E.decode(h),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){R.warn(`${u.type} decoder error:`,_)}return m})))).forEach(u=>{u.type==="h264"?(i.isH264EncodeSupported=u.encodeSupported,i.isH264DecodeSupported=u.decodeSupported):u.type==="vp8"&&(i.isVp8EncodeSupported=u.encodeSupported,i.isVp8DecodeSupported=u.decodeSupported)}),s(),o(i)}catch(n){s(),R.warn("detectWebCodecsSupported failed:",n),o(i)}})),mc)})}var PT=(o,i,e)=>{location.protocol==="http:"&&!oi&&(o[i]=()=>{throw new D({code:I.INVALID_OPERATION,message:Je.NOT_SUPPORTED_HTTP})})},Cr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(he(o.selected)&&!o.selected):!1};function Ip(){let o="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";o+=`${i} * ${e}`}return o}function Ap(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Cp(){let o={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){o.isSupported=!0;break}return o.isSupported}function Rp(){return"captureStream"in HTMLCanvasElement.prototype}function gc(){return ji||ge||qe&&qe<63?!1:!!(ou()&&Rp())}function yp(){return!(qe<74||zr||et<11||qo<46)}function Tc(){return gc()||yp()}var wT=function(){if(T(window.RTCRtpTransceiver)||!St()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:gr}),o.addTransceiver(f.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function oo(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Rr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function yr(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function St(){return et===11&&!kl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var os=!(!St()||$e&&qe<86);function LT(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var gn="RTCRtpSender"in window;function nu(){return gn&&"replaceTrack"in window.RTCRtpSender.prototype}function Tn(){return gn&&"setParameters"in window.RTCRtpSender.prototype&&Rr()}var au="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,yi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,cu=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,du=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,hi=gn&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Yo()>=86,ss="RTCRtpScriptTransform"in window,En=gn&&(hi||ss),lu=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Ec(){let o={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(o.AudioDecoder=!0),T(window.AudioEncoder)||(o.AudioEncoder=!0),T(window.VideoDecoder)||(o.VideoDecoder=!0),T(window.VideoEncoder)||(o.VideoEncoder=!0),T(window.ImageDecoder)||(o.ImageDecoder=!0),o}function bp(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function vp(){return!T(window.WebTransport)}function uu(){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 xT(){let o={browser:`${Ci.name}/${Ci.version}`,os:tc(),displayResolution:Ip(),isScreenShareSupported:_n(),isWebRTCSupported:lu(),isGetUserMediaSupported:Ap(),isWebAudioSupported:Cp(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ec(),isMediaSessionSupported:bp(),isWebTransportSupported:vp()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var Np="checkResult";function Tp(o=30){es.setItem(Np+o,{ua:navigator.userAgent,checkResult:ee})}function hu(o){Zi();let i=es.getItem(Np+o);i&&i.ua===navigator.userAgent&&i.checkResult&&UT(i.checkResult.detail,ee.detail)&&(ee=i.checkResult),_c(o)}function UT(o,i){return yt(o)?Object.keys(i).every(e=>e in o):!1}function Ki(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Sc="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function Ep(o){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[o]}var Sp=!1;function mu(){return p(this,null,function*(){var o;try{if(Sp||!((o=navigator==null?void 0:navigator.mediaCapabilities)!=null&&o.encodingInfo))return;let i=Zr(),e=wl();if(i===0||e===0)return;Sp=!0;let t=["H264","VP8","VP9","AV1","H265"],[r,s]=yield Promise.all([Dp(t),Mp(t)]);r&&Object.keys(r).forEach(c=>{let l=Ep(c.toLowerCase());v.addEnum({key:513707,value:+`${l}${+r[c].supported}${+r[c].powerEfficient}${i}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(c=>{let l=Ep(c.toLowerCase());v.addEnum({key:514713,value:+`${l}${+s[c].supported}${+s[c].powerEfficient}${i}${e}`,useUV:!1})});let{sender:n,receiver:a}=Op();v.addEnum({key:513708,value:+`${i}${e}${+n.high}`,useUV:!1}),v.addEnum({key:513709,value:+`${i}${e}${+n.main}`,useUV:!1}),v.addEnum({key:514714,value:+`${i}${e}${+a.high}`,useUV:!1}),v.addEnum({key:514715,value:+`${i}${e}${+a.main}`,useUV:!1})}catch(i){R.info("detectVideoCodecCapabilities failed",i)}})}function Dp(o,i=1920,e=1080,t=30,r=3e3){return p(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Mp(o,i=1920,e=1080,t=30,r=3e3){return p(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Op(){let o={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.sender.base=!0;break;case"4d":o.sender.main=!0;break;case"64":o.sender.high=!0;break}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.receiver.base=!0;break;case"4d":o.receiver.main=!0;break;case"64":o.receiver.high=!0;break}}})}}catch(i){R.warn("get H264 profile levelId failed",i)}return o}var Pp=Ge(at(),1);var kp=Symbol("instance"),OC=Symbol("abortCtrl"),Ic=Symbol("cacheResult"),Sn=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Cn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},In=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function VT(o){return typeof o=="object"&&o&&"then"in o}var An=new Map;function ye(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let c=An.get(t)||[];An.has(t)||An.set(t,c),c.push({from:o,to:i,action:n})}let a=s.value;s.value=function(...c){let l=this;if(e.context&&(l=J.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[Ic]:Promise.resolve(l[Ic]);l.state instanceof Sn&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(o)?o.length==0?l.state instanceof Sn&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(u=new In(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(u=new In(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let m=A=>{if(e.fail&&e.fail.call(this,A),e.sync){if(e.ignoreError)return A;throw A}else return e.ignoreError?Promise.resolve(A):Promise.reject(A)};if(u)return m(u);let h=l.state,_=new Sn(h,i,n);Cn.call(l,_);let g=A=>{var k;return l[Ic]=A,_.aborted||(Cn.call(l,i),(k=e.success)===null||k===void 0||k.call(this,l[Ic])),A},E=A=>(Cn.call(l,h,A),m(A));try{let A=a.apply(this,c);return VT(A)?A.then(g).catch(E):e.sync?g(A):Promise.resolve(g(A))}catch(A){return E(new In(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${A}`,A instanceof Error?A:new Error(String(A))))}}}}var FT=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 Cn(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit(J.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var J=class o extends Pp.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=o.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[kp];r?this.name=r.name+"-"+r.count++:t[kp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=An.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);An.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:m})=>{typeof l=="string"?r.push({from:l,to:u,action:m}):l.length?l.forEach(h=>{r.push({from:h,to:u,action:m})}):s.push({to:u,action:m})}),r.forEach(({from:l,to:u,action:m})=>{n.add(l),n.add(u),n.add(m+"ing"),t.add(`${l} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${u} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${l} : ${m} \u{1F534}`)}),s.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(m=>{m!==l&&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=o.instances.get(i),e||o.instances.set(i,e=new o(i,void 0,Object.create(o.prototype)))):(e=o.instances2.get(i),e||o.instances2.set(i,e=new o(i.constructor.name,void 0,Object.create(o.prototype)))),e}static getState(i){var e;return(e=o.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){FT(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Cn.call(this,i)}};J.STATECHANGED="stateChanged";J.UPDATEAFSM="updateAFSM";J.INIT="[*]";J.ON="on";J.OFF="off";J.instances=new Map;J.instances2=new WeakMap;var fu=typeof window!="undefined",wp=fu&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},BT=fu&&window.cancelIdleCallback||function(o){clearTimeout(o)},Lp=fu&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Fe=class Fe{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=O({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=O({delay:1e4,count:0},t):i==="raf"?t=O({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=O({delay:2e3,count:0,backgroundTask:!0},t);let r=L(O({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Fe.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Fe.sharedWorker||(Fe.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
14
14
  const timers = new Map();
15
15
  self.onmessage = function(e) {
16
16
  const { taskId, delay, type } = e.data;
@@ -23,15 +23,15 @@ Refer to: ${cp("en",a)}
23
23
  timers.delete(taskId);
24
24
  }
25
25
  };
26
- `],{type:"application/javascript"}))),Be.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Be.workerTasks.get(e.data.taskId);r&&(Be.isBreakLoop(r)?((t=Be.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Be.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Be.workerTasks.set(i.taskID,i),Be.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Be.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=U(),t,r=()=>{if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Be.isBreakLoop(i))return i.ricID=wp(r,{timeout:i.delay})};return i.ricID=wp(r,{timeout:i.delay})}static raf(i){let e=U(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=U()-e,e=U(),i.callback(),i.loopCount+=1,Be.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Be.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=U()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Lp&&Lp(r),s&&BT(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Be,"taskMap",new Map),d(Be,"currentTaskID",1),d(Be,"sharedWorker",null),d(Be,"workerTasks",new Map);var pu=Be,re=pu;var FC={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:p.SEI_MESSAGE,ERROR:"error"};var he={LOADED_DATA:p.LOADEDDATA,LOADED_META_DATA:p.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:p.RESIZE,TIME_UPDATE:"time-update"};var Ni={};Vi(Ni,{create:()=>tt,remove:()=>Le});var Rn=new WeakMap;function tt(o,i){Rn.has(o)||Rn.set(o,[]);let e=Rn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function Le(o){let i=Rn.get(o);i&&(i.forEach(e=>e()),Rn.delete(o))}var _u=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:$e,env:Fi.QCLOUD,browserVersion:Ri.name+Ri.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){si||!R.isAbleToUpload||this._configs.env===Fi.QCLOUD&&this.uploadEventToKibana(L(M({},i),{result:"success"}))}logFailedEvent(i){if(si||!R.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Fi.QCLOUD&&this.uploadEventToKibana(L(M({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:la(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:$e,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
27
- ${t.stack}`));let s=Ir.enable?Gi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Wi(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>Ji({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},oe=new _u;var Di=new WeakMap;function Ot({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ci({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,c,()=>{var _;(_=Di.get(r))!=null&&_.has(s)?l():u(c)},u,h):(m=Di.get(r))!=null&&m.has(s)?l():u(c)},onRetrying(c,l){var u;Ai(e)&&e.call(this,c,l),(u=Di.get(r))!=null&&u.has(s)&&(Di.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Di.get(r);return l?l.set(s,{args:c}):Di.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Di.get(r))==null?void 0:u.delete(s)})},n}}function yn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=Di.get(t))!=null&&c.has(o)){let{stopRetry:u,args:h}=Di.get(t).get(o),m=!0;if(e){for(let _ of h)if(!a.find(g=>g===_)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=Di.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var pi=class extends q{constructor(e,t){super(e.id,`${t}-player`);this.options=e;this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_isPausedByUserCall",!1);d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=$r,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 isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=H({key:B.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new D({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ft?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),(e=this.element)==null||e.pause(),this._isPausedByUserCall=!0,this instanceof it&&We&&qe>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():Ol?this.replay():(this.element&&this.track&&We&&qe>=128&&(this.element.srcObject=new MediaStream([this.track])),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 tt(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Ni==null||Ni.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){S.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Le(e)}unbindEvents(){this.element&&Le(this.element),this.unbindTrackEvents(),S.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:br()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE),Te&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{delay:3e3}));break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),oe.uploadEvent({log:`stat-${this.kind}-${Ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),bl||rn?this.emit(he.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(he.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(he.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),oe.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),oe.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(he.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ke(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ke(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return f(this,null,function*(){switch(e.type){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(p.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(pi,"PlayerEvent",he),O([Ot({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],pi.prototype,"doReplayByRecreateMediaStream",1),O([ye([],"PLAYING",{sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],pi.prototype,"handlePlaying",1),O([ye("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],pi.prototype,"handlePaused",1),O([ye([],"STOPPED",{sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],pi.prototype,"handleStopped",1);var er="trtc_autoplay",gu=`${er}_mask`,bn=`${er}_wrapper`,xp=`${er}_header`,Tu=`${er}_content`,Ac=`${er}_action_wrapper`,Eu=`${er}_question`,Su=`${er}_collapse`,Cc=`${er}_action_confirm`,Up=`${er}_detail`,Vp="#2473E8",Cu="dialog",HT=`${Cu}-show`,$T=`${Cu}-1`,WT=`${Cu}-2`,Bp=!1,Iu=!1,br=()=>Iu,Hp=`${ft}/${Zt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Fp=`<br><a href='${Hp}' target='_blank'>${Zt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,GT=`${Zt()?`\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${Fp}`:`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. ${Fp}`}`,Au=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Zt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Bp){let i=document.createElement("style");i.innerHTML=`.${gu}{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;}.${gu} div:not(.${Ac}){display:block !important;}.${bn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${bn} a{color:${Vp};}.${xp}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Tu}{margin:8px 0;}.${Ac}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Su}{margin-right:auto;cursor:pointer}.${Eu}{height:100%;line-height:16px;cursor:pointer;}.${Cc}{margin-left:8px;color:#fff;background:${Vp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Cc}:hover{opacity:0.9;}.${Su},.${Cc},.${Tu},.${Eu}{font-size:14px;}@media screen and (max-width:750px){.${bn}{width:80vw;}}`,document.head.appendChild(i),Bp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${gu}"><div class='${bn}'><div class='${xp}'>${location.host}</div><div class='${Tu}'>${this.content}</div><div class='${Up}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${GT}</div><div class='${Ac}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Cc,e.innerText=Zt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Eu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
26
+ `],{type:"application/javascript"}))),Fe.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Fe.workerTasks.get(e.data.taskId);r&&(Fe.isBreakLoop(r)?((t=Fe.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Fe.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Fe.workerTasks.set(i.taskID,i),Fe.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Fe.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=U(),t,r=()=>{if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Fe.isBreakLoop(i))return i.ricID=wp(r,{timeout:i.delay})};return i.ricID=wp(r,{timeout:i.delay})}static raf(i){let e=U(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=U()-e,e=U(),i.callback(),i.loopCount+=1,Fe.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Fe.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=U()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Lp&&Lp(r),s&&BT(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Fe,"taskMap",new Map),d(Fe,"currentTaskID",1),d(Fe,"sharedWorker",null),d(Fe,"workerTasks",new Map);var pu=Fe,oe=pu;var HC={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:f.SEI_MESSAGE,ERROR:"error"};var ue={LOAD_START:f.LOADSTART,LOADED_DATA:f.LOADEDDATA,LOADED_META_DATA:f.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:f.RESIZE,TIME_UPDATE:"time-update"};var vi={};Vi(vi,{create:()=>tt,remove:()=>Le});var Rn=new WeakMap;function tt(o,i){Rn.has(o)||Rn.set(o,[]);let e=Rn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function Le(o){let i=Rn.get(o);i&&(i.forEach(e=>e()),Rn.delete(o))}var _u=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:He,env:Bi.QCLOUD,browserVersion:Ci.name+Ci.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){oi||!R.isAbleToUpload||this._configs.env===Bi.QCLOUD&&this.uploadEventToKibana(L(O({},i),{result:"success"}))}logFailedEvent(i){if(oi||!R.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Bi.QCLOUD&&this.uploadEventToKibana(L(O({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:la(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:He,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
27
+ ${t.stack}`));let s=Ir.enable?Gi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Wi(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>qi({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},se=new _u;var Ni=new WeakMap;function Mt({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ai({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:m}){var h;i?i.call(this,c,()=>{var _;(_=Ni.get(r))!=null&&_.has(s)?l():u(c)},u,m):(h=Ni.get(r))!=null&&h.has(s)?l():u(c)},onRetrying(c,l){var u;Ii(e)&&e.call(this,c,l),(u=Ni.get(r))!=null&&u.has(s)&&(Ni.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Ni.get(r);return l?l.set(s,{args:c}):Ni.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Ni.get(r))==null?void 0:u.delete(s)})},n}}function yn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=Ni.get(t))!=null&&c.has(o)){let{stopRetry:u,args:m}=Ni.get(t).get(o),h=!0;if(e){for(let _ of m)if(!a.find(g=>g===_)){h=!1;break}}h&&(i&&i.apply(this,a),u&&u(),(l=Ni.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var mi=class extends J{constructor(e,t){super(e.id,`${t}-player`);this.options=e;this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_isPausedByUserCall",!1);d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isPlayCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=$r,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 isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return p(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=H({key:F.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new D({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ft?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(f.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),this._isPausedByUserCall=!0,(e=this.element)==null||e.pause()}resume(e=!1){return this._isPausedByUserCall=!1,this.doResume(e)}doResume(e=!1){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():Ml?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 tt(this.element,this.element).add(f.PLAYING,e).add(f.ENDED,e).add(f.PAUSE,e).add(f.ERROR,e).add(f.LOADSTART,e).add(f.LOADEDDATA,e).add(f.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);vi==null||vi.create(e,e).add(f.ENDED,t).add(f.MUTE,t).add(f.UNMUTE,t),e.readyState===f.ENDED&&this.handleTrackEvent({type:f.ENDED}),e.muted&&this.handleTrackEvent({type:f.MUTE})}}bindAutoPlayEvent(){S.on(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Le(e)}unbindEvents(){this.element&&Le(this.element),this.unbindTrackEvents(),S.off(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case f.PLAYING:br()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(f.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case f.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(f.ENDED);break;case f.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(f.PAUSE),ge&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this._isPausedByUserCall&&this.doResume()},{delay:3e3}));break;case f.ERROR:if(this.element&&this.element.error){this.handlePaused(f.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),se.uploadEvent({log:`stat-${this.kind}-${Ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),bl||rn?this.emit(ue.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case f.LOADEDDATA:this.kind===f.VIDEO&&this.emit(ue.LOADED_DATA);break;case f.LOADEDMETADATA:this.kind===f.VIDEO&&this.emit(ue.LOADED_META_DATA);break;case f.LOADSTART:this.emit(ue.LOAD_START);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===f.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===f.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ue.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ke(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ke(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return p(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===f.UNMUTE?"info":"warn"](`track ${t}`),t){case f.ENDED:this.handleStopped(f.ENDED);break;case f.MUTE:this.handlePaused(f.MUTE);break;case f.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this._isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(f.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(mi,"PlayerEvent",ue),M([Mt({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],mi.prototype,"doReplayByRecreateMediaStream",1),M([ye([],"PLAYING",{sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],mi.prototype,"handlePlaying",1),M([ye("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],mi.prototype,"handlePaused",1),M([ye([],"STOPPED",{sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],mi.prototype,"handleStopped",1);var er="trtc_autoplay",gu=`${er}_mask`,bn=`${er}_wrapper`,xp=`${er}_header`,Tu=`${er}_content`,Ac=`${er}_action_wrapper`,Eu=`${er}_question`,Su=`${er}_collapse`,Cc=`${er}_action_confirm`,Up=`${er}_detail`,Vp="#2473E8",Cu="dialog",$T=`${Cu}-show`,WT=`${Cu}-1`,GT=`${Cu}-2`,Fp=!1,Iu=!1,br=()=>Iu,Hp=`${ft}/${Yt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Bp=`<br><a href='${Hp}' target='_blank'>${Yt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,qT=`${Yt()?`\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${Bp}`:`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. ${Bp}`}`,Au=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Yt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Fp){let i=document.createElement("style");i.innerHTML=`.${gu}{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;}.${gu} div:not(.${Ac}){display:block !important;}.${bn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${bn} a{color:${Vp};}.${xp}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Tu}{margin:8px 0;}.${Ac}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Su}{margin-right:auto;cursor:pointer}.${Eu}{height:100%;line-height:16px;cursor:pointer;}.${Cc}{margin-left:8px;color:#fff;background:${Vp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Cc}:hover{opacity:0.9;}.${Su},.${Cc},.${Tu},.${Eu}{font-size:14px;}@media screen and (max-width:750px){.${bn}{width:80vw;}}`,document.head.appendChild(i),Fp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${gu}"><div class='${bn}'><div class='${xp}'>${location.host}</div><div class='${Tu}'>${this.content}</div><div class='${Up}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${qT}</div><div class='${Ac}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Cc,e.innerText=Yt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Eu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
28
28
  <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
29
29
  <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
30
30
  <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
31
31
  <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
32
32
  </svg>
33
- `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Zt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),oe.uploadEvent({log:HT}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||oe.uploadEvent({log:$T}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||oe.uploadEvent({log:WT}),this._isQuestionClicked=!0}},vn=null;function as(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class extends pi{constructor(e){super(e,p.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(p.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===p.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===p.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(he.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function tr(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,Jp=-1,qp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),cs()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var cs=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",cs)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),qT(),document.removeEventListener("visibilitychange",cs),document.removeEventListener("click",cs))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",cs)})}document.addEventListener("click",cs);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function qT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!Te||qp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===Jp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),Jp=rt.currentTime,Gp=U())};qp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Se=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.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=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},On=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}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(Se().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=Mn(i);e&&this.source.replaceNode(e)}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}},ds=class extends On{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Se("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function Mn(o){try{let i=zp.get(o);if(i)return i;let e=Se();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(te&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Mt=class Mt{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Mt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Mt.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Mt.workletReady=tr(Mt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Mt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Mt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Mt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),oe.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Se("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Mt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Mt,"lastMessageTime",0),d(Mt,"audioContext",Se("volume-meter")),d(Mt,"workletReady");var vc=Mt,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=Je(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&us(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(p.AUDIO,"Input"));d(this,"videoInputs",new Pn(p.VIDEO,"Input"));d(this,"audioOutputs",new Pn(p.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run("interval",()=>{this.update()},{delay:1e4}))}init(){ls().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 ls(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Se())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Oo?null:new Nu;function us(o){return o.deviceId===o.groupId&&o.groupId===""}function ls(){return f(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{us(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return f(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return f(this,null,function*(){return(Te||Pe)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!Du.has(t)}function Ou(o,i){return f(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===p.AUDIO&&o===Wr?yield Ou(e,t):!0})}var Nc,Mu=class extends On{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},hs=class o extends pi{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Se("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Mu(this._log)}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(he.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Se("player").createAnalyser()),ef(),He(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends hs{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(he.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},Oc=class extends hs{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Se("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(he.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=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!Te)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(Te)if(this.enableVolumeControlInIOS)Xp();else return;if(te&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends q{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?Oc:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof fi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof fi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(he.PLAYER_STATE_CHANGED,c=>{if(S.emit(A.PLAYER_STATE_CHANGED,M({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:m}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||m.isAvailable&&!m.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===p.VIDEO&&(this.player.on(he.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(he.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_META_DATA)}),this.player.on(he.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(he.RESIZE,c=>{this.emitFirstVideoFrameEvent(he.RESIZE),this.emit("video-size-changed",M({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(he.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get isAudio(){return this.kind===p.AUDIO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Ae(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ae(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===p.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ae(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(me(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.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){tt(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return f(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((qi||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;as()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===he.RESIZE&&!r&&!s||e===he.LOADED_META_DATA&&!r&&!s||(e===he.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};O([ye([],q.INIT,{sync:!0})],no.prototype,"close",1);var jT=Object.prototype.hasOwnProperty,{toString:Cb}=Object.prototype;function XT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(jT.call(o,i))return!1;return!0}}return!1}var _i=XT;var zT=function(o){return f(this,null,function*(){let i=YT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(M({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!me(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:B.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:B.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},QT=Ci({retryFunction:zT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Pe||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)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{oe.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{oe.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),oe.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return f(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&ue(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function YT(o){return{audio:ZT(o),video:KT(o)}}function ZT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!_i(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(Q(o.channelCount)&&(i.channelCount=o.channelCount),(me(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),me(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),me(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),_i(i)?!0:i)}function KT(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!_i(e)?e:(o.width&&(e.width={ideal:o.width},i&&!te&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!te&&(e.height.max=o.height)),te&&oi&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),_i(e)?!0:e)}var nf=QT;function Mc(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function kc(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var eE=0,Pc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++eE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=M({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},wc=new WeakMap,Lc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=wc.get(this)||new Pc;return wc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function xc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=wc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Lc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),wc.delete(this),Lc.delete(this),r.apply(this,s)},t}}function gi(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Lc.get(this)||new Map,c=a.get(s(n))||new Pc;return a.set(s(n),c),Lc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Me,Inspect:()=>$t,LastSink:()=>ao,Sink:()=>X,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>UE,bindCallback:()=>AE,bindNodeCallback:()=>CE,buffer:()=>dE,bufferCount:()=>cE,bufferTime:()=>iS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>rE,concatMap:()=>XE,concatMapTo:()=>zE,count:()=>bE,create:()=>ne,debounce:()=>VE,debounceTime:()=>BE,defer:()=>uf,delay:()=>rS,deliver:()=>z,dispose:()=>Uc,elementAt:()=>FE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>ZE,exhaustMapTo:()=>KE,expand:()=>oS,filter:()=>Wt,find:()=>HE,findIndex:()=>$E,first:()=>WE,fromAnimationFrame:()=>SE,fromArray:()=>pE,fromEvent:()=>de,fromEventPattern:()=>fE,fromFetch:()=>_E,fromIterable:()=>gE,fromPromise:()=>pf,fromReadableStream:()=>EE,fromReader:()=>TE,groupBy:()=>eS,identity:()=>tE,ignoreElements:()=>OE,iif:()=>sE,inspect:()=>df,interval:()=>Vu,last:()=>GE,map:()=>Bn,mapTo:()=>jE,max:()=>vE,merge:()=>Ln,mergeMap:()=>QE,mergeMapTo:()=>YE,min:()=>NE,never:()=>RE,nothing:()=>fe,of:()=>mE,pairwise:()=>qE,pipe:()=>le,race:()=>xu,range:()=>IE,reduce:()=>Bu,retry:()=>cS,scan:()=>mh,setAsapScheduler:()=>hE,share:()=>rr,shareReplay:()=>oE,skip:()=>kE,skipUntil:()=>PE,skipWhile:()=>$c,startWith:()=>xn,subject:()=>ot,subscribe:()=>Ee,sum:()=>DE,switchMap:()=>Or,switchMapTo:()=>mo,take:()=>or,takeLast:()=>ME,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Fn,throttle:()=>LE,throwError:()=>yE,timeInterval:()=>tS,timeout:()=>aS,timer:()=>Un,toPromise:()=>sS,toReadableStream:()=>nS,withLatestFrom:()=>aE,zip:()=>nE});function fe(...o){}var cf=o=>o(),tE=o=>o;function Uc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",iE=1,$t=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Me.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=fe,this.error=fe,this.next=fe,this.dispose=fe,this.subscribe=fe,this.doDefer()}subscribe(i){return i instanceof $t?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),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}},X=class extends ao{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)}},co=class extends ao{constructor(i,e=fe,t=fe,r=fe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=fe,i instanceof $t){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Me.defer(s,0)}),Me.create(s),Me.pipe(s),this.sourceId=s.id,this.subscribe(i),Me.subscribe({id:s.id,end:!0}),e==fe?this._next=n=>Me.next(s,0,n):this.next=n=>{Me.next(s,0,n),e(n)},r==fe?this._complete=()=>Me.complete(s,0):this.complete=()=>{this.dispose(),Me.complete(s,0),r()},t==fe?this._error=n=>Me.complete(s,0,n):this.error=n=>{this.dispose(),Me.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function le(o,...i){return i.reduce((e,t)=>t(e),o)}function ne(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,$t.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}});Me.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof $t&&Me.addSource(t,s)}return t}return o}function z(o,i){return function(...e){return t=>{if(t instanceof $t){let r=ne(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Me.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends X{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Me.defer(this.source,this.id)})}next(i){Me.next(this.source,this.id,i),this.sink.next(i)}complete(){Me.complete(this.source,this.id),this.sink.complete()}error(i){Me.complete(this.source,this.id,i),this.sink.error(i)}},Me={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=iE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Vc=class extends ao{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 rr(){return o=>{let i=new Vc(o);if(o instanceof $t){let e=ne(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Me.pipe(e),e}return ne(i.add.bind(i),"share",arguments)}}function Ln(...o){return ne(i=>{let e=new X(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ne(i=>{let e=new Map;o.forEach(t=>{let r=new X(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function rE(...o){return ne(i=>{let e=0,t=o.length,r=new X(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function oE(o){return i=>{let e=new Vc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ne(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function sE(o,i,e){return ne(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ne(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new X(i);u.next=h=>{t--,u.next=m=>{s[l]=m,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function nE(...o){return ne(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new X(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ne((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends X{constructor(i,...e){super(i);let t=new X(this.sink);t.next=r=>this.buffer=r,t.complete=fe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},aE=z(Pu,"withLatestFrom"),wu=class extends X{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()}},cE=z(wu,"bufferCount"),Lu=class extends X{constructor(i,e){super(i),this.buffer=[];let t=new X(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=fe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},dE=z(Lu,"buffer");var lE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ne(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=fe,e.complete=fe,e.error=fe,e}function uf(o){return ne(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},uE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=uE(),hf=o=>i=>{Uu(()=>o(i))},hE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function mE(...o){return ne(mf(o),"of",arguments)}function pE(o){return ne(mf(o),"fromArray",arguments)}function Vu(o){return ne(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ne(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Bc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function fE(o,i){return ne(Bc(o,i),"fromEventPattern",arguments)}function de(o,i){if("on"in o&&"off"in o)return ne(Bc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ne(Bc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ne(Bc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ne(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function _E(o,i){return ne(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function gE(o){return ne(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function TE(o){let i=e=>lE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ne(e=>{i(e)},"fromReader",arguments)}function EE(o){return ne(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function SE(){return ne(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function IE(o,i){return ne((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function AE(o,i,...e){return ne(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function CE(o,i,...e){return ne(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function RE(){return ne(()=>{},"never",arguments)}function yE(o){return ne(i=>i.error(o),"throwError",arguments)}function Vn(){return ne(o=>o.complete(),"empty",arguments)}var lo=class extends X{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Bu=z(lo,"reduce"),bE=o=>z(lo,"count")((i,e)=>o(e)?i+1:i,0),vE=()=>z(lo,"max")(Math.max),NE=()=>z(lo,"min")(Math.min),DE=()=>z(lo,"sum")((o,i)=>o+i,0);var Fu=class extends X{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Wt=z(Fu,"filter"),Hu=class extends X{next(i){}},OE=z(Hu,"ignoreElements"),$u=class extends X{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=z($u,"take"),Wu=class extends X{constructor(i,e){super(i);let t=new X(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=Uc,t.subscribe(e)}},ke=z(Wu,"takeUntil"),Gu=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=z(Gu,"takeWhile"),ME=o=>Bu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Ju=class extends X{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},kE=z(Ju,"skip"),qu=class extends X{constructor(i,e){super(i),i.next=fe;let t=new X(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=Uc,t.subscribe(e)}},PE=z(qu,"skipUntil"),ju=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},$c=z(ju,"skipWhile"),wE={leading:!0,trailing:!1},Xu=class extends X{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)}},Fc=class extends X{constructor(i,e,t=wE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=fe,this._throttle.complete(),super.complete()}},LE=z(Fc,"throttle"),xE={leading:!1,trailing:!0},UE=o=>z(Fc,"audit")(o,xE),zu=class extends X{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Hc=class extends X{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(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()}},VE=z(Hc,"debounce"),BE=o=>z(Hc,"debounceTime")(i=>Un(o)),Qu=class extends X{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),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()}},FE=z(Qu,"elementAt"),HE=o=>i=>or(1)($c(e=>!o(e))(i)),Yu=class extends X{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},$E=z(Yu,"findIndex"),Zu=class extends X{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.doDefer(),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()}},WE=z(Zu,"first"),Ku=class extends X{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()}},GE=z(Ku,"last"),eh=class extends X{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.doDefer(),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()}},JE=z(eh,"every");var th=class extends X{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=z(th,"scan"),ih=class extends X{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},qE=z(ih,"pairwise"),Wc=class extends X{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Bn=z(Wc,"map"),jE=o=>z(Wc,"mapTo")(i=>o),uo=class extends X{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()}},ho=class o extends X{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===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Gc=class extends uo{},Jc=class extends ho{next(i){this.subInner(i,Gc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Gc)}}},Or=z(Jc,"switchMap");function zc(o){return(i,e)=>o(()=>i,e)}var mo=zc(z(Jc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{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(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},XE=z(qc,"concatMap"),zE=zc(z(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},QE=z(jc,"mergeMap"),YE=zc(z(jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},Xc=class extends ho{next(i){this.next=fe,this.subInner(i,sh)}},ZE=z(Xc,"exhaustMap"),KE=zc(z(Xc,"exhaustMapTo")),nh=class extends X{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=ot(),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)}},eS=z(nh,"groupBy"),ah=class extends X{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}},tS=z(ah,"timeInterval"),ch=class extends X{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()}},iS=z(ch,"bufferTime"),dh=class extends X{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},rS=z(dh,"delay"),lh=class extends X{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=z(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},oS=z(hh,"expand");var sS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),nS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ee=(o=fe,i=fe,e=fe)=>t=>new co(t,o,i,e),fh=class extends X{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)}))}},Fn=z(fh,"tap"),_h=class extends X{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},aS=z(_h,"timeout"),cS=(o=1/0)=>i=>{if(i instanceof $t){let e=ne(t=>{let r=o,s=new X(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Me.pipe(e),e}else return e=>{let t=o,r=new X(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(p.MUTE,this.onTrackMuted),e.addEventListener(p.UNMUTE,this.onTrackUnmuted),e.addEventListener(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(p.MUTE,this.onTrackMuted),e.removeEventListener(p.UNMUTE,this.onTrackUnmuted),e.removeEventListener(p.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=ei(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return f(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>f(this,null,function*(){var l,u,h,m;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===q.INIT||this.state==="ready")&&s(),le(de(e,"local-publish-flag-changed"),Wt(()=>this.hasFlag),ke(Ln(de(this,q.INIT),de(this,"ready"))),Ee(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((m=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:m.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var g,E,C,k,ae,w,Ye;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let j=this.mediaTrack.stats.totalFrames||0;j-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",j)}let N=this.kind===p.AUDIO,y=this.stat.bytesSent>0;if(v[y?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let j=((ae=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:ae.toUpperCase())||"H264",ge={H264:513704,H265:513705,VP8:513706}[j];ge&&v[y?"addSuccessEvent":"addFailedEvent"]({key:ge})}if(!y){if(v.addEnum({key:N?503701:513703,value:Zr()}),oe.uploadEvent({log:`stat-encode-failed-${this.kind}-${ni()||ai()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Ye=(w=this.room)==null?void 0:w.videoCodec)==null?void 0:Ye.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&bi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ls().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===p.AUDIO&&!rf(this.sourceTrack)||this.kind===p.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&oi&&Pe)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Po){setTimeout(()=>this.onTrackMuted(),Po);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Te||_e)&&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(He(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<Po){setTimeout(()=>this.onTrackEnded(),Po);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof Xe;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};O([ye(q.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),O([ir()],po.prototype,"capture",1),O([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),O([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var fi=po,Hn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends fi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ds(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return f(this,null,function*(){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:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield He(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield He(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Ou(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.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(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(te||Pe?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Te&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Se().createGain()),this._output.setNode(Se().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Pe||Te))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(qe<=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.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=Mn(e);if(!r)return;let s=new xe,n=Se().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield He(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield He(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Bi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}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 s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let s=0;s<t.byteLength;s++,e++)r.setInt8(s,this.dataView.getInt8(e));return r}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){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=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,_)=>m+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let _=0;_<n[m].dataView.byteLength;_++)l.setInt8(h++,n[m].dataView.getInt8(_));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Mr=class Mr extends fi{constructor(e,t=4){super(t,it);d(this,"profile",M({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Vt(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(M({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!bi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return f(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,He(Mr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),He(Mr.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return He(Mr.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Vt(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(M({},this.profile),{width:1920,height:1080}))}}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return bi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:$o(this.settings,this.profile)}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)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.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}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(rn&&!Yo&&du){let r=(yield At(!0)).map(n=>{var a;return L(M({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,m,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(m=s.capabilities.width)!=null&&m.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=M({},e);return e.width*e.height<=160*120&&_e&&We&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ml&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(We||te)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield He(Mr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield He(Mr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};O([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Mr.prototype,"capture",1);var Xe=Mr;var Eh={};Vi(Eh,{REPORT_TYPE:()=>Wo,buildSSOPackage:()=>Gi,bytes2ms:()=>Om,calculateScaleResolutionDownNumber:()=>$o,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>qs,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ti,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>Bm,getConstructorName:()=>Uo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>ei,getNetworkType:()=>ba,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Kt,getStringByteLength:()=>Js,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Oe,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Bo,isArray:()=>Ae,isAudioWorkletSupported:()=>wm,isBoolean:()=>me,isConstructor:()=>jr,isEmpty:()=>Vo,isFunction:()=>ue,isLangChinese:()=>Zt,isMediaStreamTrack:()=>km,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Vt,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Ho,loadVideo:()=>Fm,ms2bytes:()=>Mm,ms2samples:()=>fl,normalizeUrl:()=>Oa,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var uS=[-1,-1,1,-1,-1,1,1,1],hS=[0,0,1,0,0,1,1,1];var kr=class kr extends q{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof ze){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(hS),this.positionBuffer=this.createBuffer(uS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Fe&&this.render(e)||this.context instanceof ze&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Fe){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let h=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},M({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),O([ye(q.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),O([ye("connected",q.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),O([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var mS=le(Vu(250),Bn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();le(mS,$c(t=>t-e<o),or(1))(i)};var fS=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof ze?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(fS)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Fe){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),re.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",de(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=de(this._videoTrack,"mute"),le(de(this._videoTrack,"ended"),ke(this._closedOb),Ee(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=le(this._muteOb,ke(this._closedOb),mo(_f(5e3)),Wt(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Ee(()=>{this.context.destroy(new D({code:I.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()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,M({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),le(this._canvasRendered,xn(this._image),Or(r=>r instanceof HTMLCanvasElement?de(r,"rendered"):Vn()),ke(de(this,"closed")),Ee(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",le(de(this._player,he.PLAYER_STATE_CHANGED),ke(de(this,"closed")),Wt(({state:s})=>s==="PLAYING"),Ee(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Gt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(M({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
34
- `);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*c)}};var gS=`
33
+ `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:$T}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(C.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:WT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||se.uploadEvent({log:GT}),this._isQuestionClicked=!0}},vn=null;function ns(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class o extends mi{constructor(e){super(e,f.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit","cover");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});d(this,"posterImg");d(this,"_originContainerPosition");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(f.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"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(f.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===f.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===f.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===f.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===f.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===f.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(ue.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||K)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;width:100%;height:auto;aspect-ratio:${this.element.videoWidth/this.element.videoHeight};max-height: 100%;`,s.onload=()=>p(this,null,function*(){var n;s.decode&&(yield s.decode()),this.container&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&this._originContainerPosition&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}pause(e=!0){return p(this,null,function*(){return($e&&qe>=128||e&&(K||Re))&&(yield this.setPoster(this.getVideoFrame(),!0)),Pe(o.prototype,this,"pause").call(this)})}resume(e=!1){return this.posterImg&&this.setPoster("",!0),super.resume(e)}doResume(e=!1){return e&&this.element&&this.track&&$e&&qe>=128&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return p(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else if(e.msRequestFullscreen)yield e.msRequestFullscreen();else throw this._log.warn("fullscreen API not supported"),new Error("Fullscreen API not supported");this._log.info("entered fullscreen mode")}catch(t){throw this._log.error("failed to enter fullscreen:",t),t}})}exitFullscreen(){return p(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else if(document.msExitFullscreen)yield document.msExitFullscreen();else throw this._log.warn("exit fullscreen API not supported"),new Error("Exit fullscreen API not supported");this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return e?(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}toggleFullscreen(){return p(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return p(this,null,function*(){if(!this.element)throw new Error("No video element available for picture-in-picture");if(this.canvas&&this.mode!==1)throw new Error("Picture-in-picture is not supported for canvas-only mode");let{element:e}=this;try{if(this._log.warn(!!e.requestPictureInPicture,!!e.webkitSetPresentationMode),e.requestPictureInPicture){this._log.info("requestPictureInPicture");let t=yield e.requestPictureInPicture();return this._log.info("entered picture-in-picture mode"),t}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered picture-in-picture mode (webkit)"),{};throw new Error("Picture-in-picture API not supported")}catch(t){throw this._log.error("failed to enter picture-in-picture:",t.name,t.message),t}})}exitPictureInPicture(){return p(this,null,function*(){try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this._log.info("exited picture-in-picture mode");else if(this.element&&this.element.webkitSetPresentationMode)yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited picture-in-picture mode (webkit)");else throw this._log.warn("exit picture-in-picture API not supported or not in PiP mode"),new Error("Exit picture-in-picture API not supported or not in PiP mode")}catch(e){throw this._log.error("failed to exit picture-in-picture:",e),e}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:e.webkitPresentationMode?e.webkitPresentationMode==="picture-in-picture":!1}togglePictureInPicture(){return p(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function tr(o,i){return p(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,qp=-1,Jp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var as=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",as)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),jT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function jT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!ge||Jp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===qp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),qp=rt.currentTime,Gp=U())};Jp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.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=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Mn=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}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(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=On(i);e&&this.source.replaceNode(e)}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}},cs=class extends Mn{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function On(o){try{let i=zp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(K&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Ot,"lastMessageTime",0),d(Ot,"audioContext",Ee("volume-meter")),d(Ot,"workletReady");var vc=Ot,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=Ge(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(f.AUDIO,"Input"));d(this,"videoInputs",new Pn(f.VIDEO,"Input"));d(this,"audioOutputs",new Pn(f.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){ds().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield ds(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new Nu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function ds(){return p(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===f.AUDIO_INPUT?e.audio=!0:t.kind===f.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return p(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return p(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.AUDIO_INPUT}`;return!!Du.has(t)}function Mu(o,i){return p(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return p(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===f.AUDIO&&o===Wr?yield Mu(e,t):!0})}var Nc,Ou=class extends Mn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends mi{constructor(e){super(e,f.AUDIO);d(this,"_outputDeviceId");d(this,"_floatVolume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Ou(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,this.setVolume(z(e)?e/100:this._floatVolume),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(ue.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return p(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),ef(),Pe(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},hs=class extends us{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.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=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Xp();else return;if(K&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends J{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?hs:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof pi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{if(S.emit(C.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:m,remoteAuxiliaryTrack:h}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||m.isAvailable&&!m.player.isPlaying||h.isAvailable&&!h.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===f.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),S.emit(C.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(ue.RESIZE,c=>{this.emitFirstVideoFrameEvent(ue.RESIZE),this.emit("video-size-changed",O({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?f.AUDIO:f.VIDEO}get isAudio(){return this.kind===f.AUDIO}get strMediaType(){return this.mediaType===4?f.VIDEO:this.mediaType===2?f.SCREEN:f.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return p(this,null,function*(){let r=Ie(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ie(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===f.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(C.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ie(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==f.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===f.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?C.TRACK_MUTED:C.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){tt(e,e).add(f.MUTE,this.onTrackMuted).add(f.UNMUTE,this.onTrackUnmuted).add(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return p(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Ji||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(C.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.RESIZE&&!r&&!s||e===ue.LOADED_META_DATA&&!r&&!s||(e===ue.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};M([ye([],J.INIT,{sync:!0})],no.prototype,"close",1);var XT=Object.prototype.hasOwnProperty,{toString:Db}=Object.prototype;function zT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(XT.call(o,i))return!1;return!0}}return!1}var fi=zT;var QT=function(o){return p(this,null,function*(){let i=ZT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(O({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!he(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:F.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:F.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},YT=Ai({retryFunction:QT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||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)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return p(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function ZT(o){return{audio:KT(o),video:eE(o)}}function KT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!fi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(z(o.channelCount)&&(i.channelCount=o.channelCount),(he(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),he(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),he(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),fi(i)?!0:i)}function eE(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!fi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!K&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!K&&(e.height.max=o.height)),K&&ri&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),fi(e)?!0:e)}var nf=YT;function Mc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Q((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Oc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Q(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var tE=0,kc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++tE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=O({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pc=new WeakMap,wc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pc.get(this)||new kc;return Pc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Lc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Pc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=wc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),Pc.delete(this),wc.delete(this),r.apply(this,s)},t}}function _i(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=wc.get(this)||new Map,c=a.get(s(n))||new kc;return a.set(s(n),c),wc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Q((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>j,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>VE,bindCallback:()=>CE,bindNodeCallback:()=>RE,buffer:()=>lE,bufferCount:()=>dE,bufferTime:()=>rS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>oE,concatMap:()=>zE,concatMapTo:()=>QE,count:()=>vE,create:()=>ae,debounce:()=>FE,debounceTime:()=>BE,defer:()=>uf,delay:()=>oS,deliver:()=>X,dispose:()=>xc,elementAt:()=>HE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>KE,exhaustMapTo:()=>eS,expand:()=>sS,filter:()=>$t,find:()=>$E,findIndex:()=>WE,first:()=>GE,fromAnimationFrame:()=>IE,fromArray:()=>fE,fromEvent:()=>ce,fromEventPattern:()=>_E,fromFetch:()=>gE,fromIterable:()=>TE,fromPromise:()=>pf,fromReadableStream:()=>SE,fromReader:()=>EE,groupBy:()=>tS,identity:()=>iE,ignoreElements:()=>OE,iif:()=>nE,inspect:()=>df,interval:()=>Vu,last:()=>qE,map:()=>Fn,mapTo:()=>XE,max:()=>NE,merge:()=>Ln,mergeMap:()=>YE,mergeMapTo:()=>ZE,min:()=>DE,never:()=>yE,nothing:()=>pe,of:()=>pE,pairwise:()=>jE,pipe:()=>de,race:()=>xu,range:()=>AE,reduce:()=>Fu,retry:()=>dS,scan:()=>mh,setAsapScheduler:()=>mE,share:()=>rr,shareReplay:()=>sE,skip:()=>PE,skipUntil:()=>wE,skipWhile:()=>Hc,startWith:()=>xn,subject:()=>ot,subscribe:()=>Te,sum:()=>ME,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>kE,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Bn,throttle:()=>xE,throwError:()=>bE,timeInterval:()=>iS,timeout:()=>cS,timer:()=>Un,toPromise:()=>nS,toReadableStream:()=>aS,withLatestFrom:()=>cE,zip:()=>aE});function pe(...o){}var cf=o=>o(),iE=o=>o;function xc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",rE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=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=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),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}},j=class extends ao{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)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function de(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.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}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function X(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends j{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=rE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Uc=class extends ao{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 rr(){return o=>{let i=new Uc(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new j(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new j(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function oE(...o){return ae(i=>{let e=0,t=o.length,r=new j(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function sE(o){return i=>{let e=new Uc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function nE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new j(i);u.next=m=>{t--,u.next=h=>{s[l]=h,t===0&&i.next(s)},u.next(m)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function aE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new j(i),u=[];r[c]=u,l.next=m=>{u.push(m),r.every(h=>h.length)&&i.next(r.map(h=>h.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends j{constructor(i,...e){super(i);let t=new j(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},cE=X(Pu,"withLatestFrom"),wu=class extends j{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()}},dE=X(wu,"bufferCount"),Lu=class extends j{constructor(i,e){super(i),this.buffer=[];let t=new j(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},lE=X(Lu,"buffer");var uE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function uf(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},hE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=hE(),hf=o=>i=>{Uu(()=>o(i))},mE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function pE(...o){return ae(mf(o),"of",arguments)}function fE(o){return ae(mf(o),"fromArray",arguments)}function Vu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function _E(o,i){return ae(Vc(o,i),"fromEventPattern",arguments)}function ce(o,i){if("on"in o&&"off"in o)return ae(Vc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function gE(o,i){return ae(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function TE(o){return ae(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function EE(o){let i=e=>uE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function SE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function IE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function AE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function CE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function RE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function yE(){return ae(()=>{},"never",arguments)}function bE(o){return ae(i=>i.error(o),"throwError",arguments)}function Vn(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends j{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Fu=X(lo,"reduce"),vE=o=>X(lo,"count")((i,e)=>o(e)?i+1:i,0),NE=()=>X(lo,"max")(Math.max),DE=()=>X(lo,"min")(Math.min),ME=()=>X(lo,"sum")((o,i)=>o+i,0);var Bu=class extends j{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=X(Bu,"filter"),Hu=class extends j{next(i){}},OE=X(Hu,"ignoreElements"),$u=class extends j{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=X($u,"take"),Wu=class extends j{constructor(i,e){super(i);let t=new j(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=xc,t.subscribe(e)}},ke=X(Wu,"takeUntil"),Gu=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=X(Gu,"takeWhile"),kE=o=>Fu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),qu=class extends j{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},PE=X(qu,"skip"),Ju=class extends j{constructor(i,e){super(i),i.next=pe;let t=new j(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=xc,t.subscribe(e)}},wE=X(Ju,"skipUntil"),ju=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hc=X(ju,"skipWhile"),LE={leading:!0,trailing:!1},Xu=class extends j{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)}},Fc=class extends j{constructor(i,e,t=LE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(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=pe,this._throttle.complete(),super.complete()}},xE=X(Fc,"throttle"),UE={leading:!1,trailing:!0},VE=o=>X(Fc,"audit")(o,UE),zu=class extends j{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bc=class extends j{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(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()}},FE=X(Bc,"debounce"),BE=o=>X(Bc,"debounceTime")(i=>Un(o)),Qu=class extends j{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),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()}},HE=X(Qu,"elementAt"),$E=o=>i=>or(1)(Hc(e=>!o(e))(i)),Yu=class extends j{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},WE=X(Yu,"findIndex"),Zu=class extends j{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.doDefer(),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()}},GE=X(Zu,"first"),Ku=class extends j{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()}},qE=X(Ku,"last"),eh=class extends j{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.doDefer(),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()}},JE=X(eh,"every");var th=class extends j{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=X(th,"scan"),ih=class extends j{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},jE=X(ih,"pairwise"),$c=class extends j{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Fn=X($c,"map"),XE=o=>X($c,"mapTo")(i=>o),uo=class extends j{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()}},ho=class o extends j{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===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wc=class extends uo{},Gc=class extends ho{next(i){this.subInner(i,Wc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wc)}}},Mr=X(Gc,"switchMap");function Xc(o){return(i,e)=>o(()=>i,e)}var mo=Xc(X(Gc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{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(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},zE=X(qc,"concatMap"),QE=Xc(X(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},YE=X(Jc,"mergeMap"),ZE=Xc(X(Jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jc=class extends ho{next(i){this.next=pe,this.subInner(i,sh)}},KE=X(jc,"exhaustMap"),eS=Xc(X(jc,"exhaustMapTo")),nh=class extends j{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=ot(),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)}},tS=X(nh,"groupBy"),ah=class extends j{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}},iS=X(ah,"timeInterval"),ch=class extends j{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()}},rS=X(ch,"bufferTime"),dh=class extends j{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},oS=X(dh,"delay"),lh=class extends j{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=X(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},sS=X(hh,"expand");var nS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),aS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),fh=class extends j{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)}))}},Bn=X(fh,"tap"),_h=class extends j{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},cS=X(_h,"timeout"),dS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new j(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new j(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(f.MUTE,this.onTrackMuted),e.addEventListener(f.UNMUTE,this.onTrackUnmuted),e.addEventListener(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(f.MUTE,this.onTrackMuted),e.removeEventListener(f.UNMUTE,this.onTrackUnmuted),e.removeEventListener(f.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return p(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(C.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(C.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(C.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return p(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>p(this,null,function*(){var l,u,m,h;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===J.INIT||this.state==="ready")&&s(),de(ce(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(ce(this,J.INIT),ce(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((h=(m=this.mediaTrack)==null?void 0:m.stats)==null?void 0:h.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>p(this,null,function*(){var g,E,A,k,re,P,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((A=this.mediaTrack)!=null&&A.stats){let te=this.mediaTrack.stats.totalFrames||0;te-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",te)}let N=this.kind===f.AUDIO,b=this.stat.bytesSent>0;if(v[b?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let te=((re=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:re.toUpperCase())||"H264",ve={H264:513704,H265:513705,VP8:513706}[te];ve&&v[b?"addSuccessEvent":"addFailedEvent"]({key:ve})}if(!b){if(v.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${si()||ni()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(C.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.sourceTrack&&yi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ds().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===f.AUDIO&&!rf(this.sourceTrack)||this.kind===f.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&ri&&Re)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Pe(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return p(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};M([ye(J.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),M([ir()],po.prototype,"capture",1),M([ye("ready","publish",{ignoreError:!0,success(){S.emit(C.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),M([Q(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var pi=po,Hn=new Map;S.on(C.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends pi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new cs(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return p(this,null,function*(){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:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Pe(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return p(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield Pe(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Mu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(C.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(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(K||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(qe<=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.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=On(e);if(!r)return;let s=new xe,n=Ee().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return p(this,null,function*(){try{yield Pe(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Pe(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Fi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};function zc(o,i=!1){let e=new DataView(o),t=[],r=0;for(;r<e.byteLength;){let s=0;if(r+4<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===0&&e.getUint8(r+3)===1)s=4;else if(r+3<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===1)s=3;else{r+=1;continue}let n=-1;for(let m=r+s;m<e.byteLength;m+=1){if(m+4<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===0&&e.getUint8(m+3)===1){n=m;break}if(m+3<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===1){n=m;break}}let a=n===-1?e.byteLength:n,c=a-r,l=new ArrayBuffer(c),u=new DataView(l);for(let m=0;m<c;m+=1)u.setUint8(m,e.getUint8(r+m));t.push(new sr(u,i)),r=a}return t}var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a===0?r+=1:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i+=1,this.dataView.getUint8(e)===255);e+=1);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let n=6;n<this.dataView.buffer.byteLength;n+=1){let a=this.dataView.getUint8(n);if(e+=1,a===255)i+=255;else{i+=a;break}}let t=new ArrayBuffer(i),r=new DataView(t),s=e;for(let n=0;n<t.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(s+n));return r}get naluType(){let i=this.getStartCodeLength();return i>=this.dataView.byteLength?0:this.dataView.getUint8(i)&31}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){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=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((h,_)=>h+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),m=0;for(let h=0;h<n.length;h++)for(let _=0;_<n[h].dataView.byteLength;_++)l.setInt8(m++,n[h].dataView.getInt8(_));for(let h=0;h<i.data.byteLength;h++)l.setInt8(m++,u.getInt8(h));return i.data=c,n.length}return 0}};var Or=class Or extends pi{constructor(e,t=4){super(t,it);d(this,"profile",O({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(O({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!yi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return p(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Pe(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Pe(Or.prototype,this,"setMute").call(this,e)})}capture(a){return p(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return Pe(Or.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(O({},this.profile),{width:1920,height:1080}))}}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:f.VIDEO,videoType:f.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return yi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(C.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}})}getDeviceIdWhenUsingBackCamera(){return p(this,null,function*(){let e;try{if(rn&&!Qo&&du){let r=(yield At(!0)).map(n=>{var a;return L(O({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,m,h,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((m=a.height)!=null&&m.max)?a.width.max*a.height.max:0,l=(h=s.capabilities.width)!=null&&h.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=O({},e);return e.width*e.height<=160*120&&_e&&$e&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ol&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&($e||K)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Pe(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Pe(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};M([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var Eh={};Vi(Eh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var hS=[-1,-1,1,-1,-1,1,1,1],mS=[0,0,1,0,0,1,1,1];var kr=class kr extends J{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(mS),this.positionBuffer=this.createBuffer(hS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Be&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Be){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let m=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(m?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(m?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var m;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},O({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),M([ye(J.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),M([ye("connected",J.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),M([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var pS=de(Vu(250),Fn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();de(pS,Hc(t=>t-e<o),or(1))(i)};var _S=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(_S)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Be){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ce(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ce(this._videoTrack,"mute"),de(ce(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,ke(this._closedOb),mo(_f(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new D({code:I.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()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,O({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),de(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?ce(r,"rendered"):Vn()),ke(ce(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ce(this._player,ue.PLAYER_STATE_CHANGED),ke(ce(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(O({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
34
+ `);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*c)}};var TS=`
35
35
  // \u9876\u70B9\u7740\u8272\u5668
36
36
  attribute vec4 a_position;
37
37
  attribute vec2 a_texCoord;
@@ -41,7 +41,7 @@ void main() {
41
41
  gl_Position = a_position;
42
42
  v_texCoord = a_texCoord;
43
43
  }
44
- `,TS=`
44
+ `,ES=`
45
45
  // \u7247\u5143\u7740\u8272\u5668
46
46
  precision mediump float;
47
47
  varying vec2 v_texCoord;
@@ -49,32 +49,38 @@ uniform sampler2D u_texture;
49
49
 
50
50
  void main() {
51
51
  gl_FragColor = texture2D(u_texture, v_texCoord);
52
- } `;var _o=class extends q{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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 Gt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var ES={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",ES),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,gS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,TS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),O([ye(q.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),O([ye("created",q.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var Fe=_s,ze=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,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})}};O([ye(q.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],ze.prototype,"create",1),O([ye("created",q.INIT,{ignoreError:!0,sync:!0})],ze.prototype,"destroy",1);function SS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(h)||(_.layout.rotation=h),T(m)||(_.layout.hidden=m),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Fe&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=SS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Fe)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var IS=[1,0,0,0,1,1,0,1],Jt=class extends Ue{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Fe)try{this.setTexBuffer(IS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends fi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new ze({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Gt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Gt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Jt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Jt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Jt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Jt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Jt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Jt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Jt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),re.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var AS=function(o){return f(this,null,function*(){let i=null,e=yS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Ko&&qe<74||Pe||te)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield CS(r,o.captureElement))}if(o.audio){let s=RS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function CS(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ue(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function RS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function yS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Pe?{max:o.width}:{ideal:o.width,max:o.width},height:Pe?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=AS;var Pt=class extends Xe{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof D?h:new D({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};O([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var bS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Se("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([bS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let _=URL.createObjectURL(new Blob(n[m])),g=document.createElement("a");g.href=_,g.download=`${r[m]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(m=>m.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,ae,w;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(w=(ae=this.room)==null?void 0:ae.remotePublishedUserMap.get(t))==null?void 0:w.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Se().createMediaStreamSource(new MediaStream([E]));return Gn([C],s,n,a).then(Ye=>Ye.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),h=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),m=N[0][1].subarray(c-_)),_+=c-_):(h&&(l.set(h,_),_+=h.length,h=void 0),m&&(u.set(m,_),m=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ti)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof Ti}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Y((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(de(this,Mi.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new q(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new q(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),le(Ln(de(this,q.STATECHANGED),de(this.remotePublishState,q.STATECHANGED)),Bn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ee(c=>{this.availableState.state!==(c?q.ON:q.OFF)&&(this.availableState.state=c?q.ON:q.OFF),this.updatePlayingState(c)}));let s=le(de(this.player,he.ERROR),Wt(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=le(Un(5e3),Wt(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=le(xu(s,n),ke(de(this,q.INIT)));le(this._triggerCheckDecodeSubject,Wt(()=>!this.ignoreDecodeError),mo(a),Ee(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===q.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===p.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:os[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),oe.uploadEvent({log:`stat-decode-failed-${this.kind}-${ni()||ai()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?q.ON:q.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),O([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),O([ye(q.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),O([ye(Mi.STATE_SUBSCRIBE,q.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var Ti=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&mi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);le(de(e,"mousedown"),Fn(this.startDrag.bind(this)),Or(()=>le(de(window,"mousemove"),ke(de(window,"mouseup")))),t,Ee(this.doDrag.bind(this))),le(de(e,"dblclick"),t,Ee(this.resetPosition.bind(this))),le(de(e,"wheel"),t,Ee(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,m=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let k=(E*s+C)*4,ae=C+g,w=(E*s+ae)*4,Ye=h[w];h[w+3]=0;let N=Ye>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let k=(E*s+C)*4,w=((E+g)*s+C)*4,Ye=h[w];h[w+3]=0;let N=Ye>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&m}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function DS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var ki=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new ze({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=DS(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends ki{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{ve(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{ve(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),ve(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),ve(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,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&&ve(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&ve(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ve(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ve(o.userId,e)}});function ve(o,i){let e=L(M({},i),{timestamp:Bi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).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 Ss.delete(o),i}return[]}function Sf(...o){return Y((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ae(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),ue(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Oe(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?Uo(c):ie(c)?c:Oe(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Oe(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&Q(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&Q(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&Q(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ue(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ae(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ue(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=Je(at(),1);var od=class extends If.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=ei(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}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:ei(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.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>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var MS="2025-12-06 23:07:01",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",$e),si||R.debug("Build Time:",MS);let i=`UA: ${navigator.userAgent}
53
- CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ii)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var $={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},wt=(b=>(b[b.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",b[b.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",b[b.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",b[b.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",b[b.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",b[b.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",b[b.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",b[b.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",b[b.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",b[b.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",b[b.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",b[b.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",b[b.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",b[b.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",b[b.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",b[b.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",b[b.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",b[b.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",b[b.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",b[b.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",b[b.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",b[b.INVALID_OPERATION=5100]="INVALID_OPERATION",b[b.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",b[b.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",b[b.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",b[b.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",b[b.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",b[b.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",b[b.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",b[b.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",b[b.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",b[b.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",b[b.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",b[b.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",b[b.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",b[b.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",b[b.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",b[b.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",b[b.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",b[b.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",b[b.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",b[b.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",b[b.DEVICE_ERROR=5300]="DEVICE_ERROR",b[b.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",b[b.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",b[b.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",b[b.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",b[b.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",b[b.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",b[b.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",b[b.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",b[b.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",b[b.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",b[b.SERVER_ERROR=5400]="SERVER_ERROR",b[b.NEED_TO_BUY=5401]="NEED_TO_BUY",b[b.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",b[b.OPERATION_FAILED=5500]="OPERATION_FAILED",b[b.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",b[b.REJOIN_FAILED=5502]="REJOIN_FAILED",b[b.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",b[b.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",b[b.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",b[b.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",b[b.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",b[b.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",b[b.OPERATION_ABORT=5998]="OPERATION_ABORT",b[b.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",b))(wt||{});function yf({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=wt[o];try{r=Rf[s]}catch(n){r=Rf.UNKNOWN_ERROR}return ue(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Rf=L(M({},je),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' 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:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' 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:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' 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:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Rh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=yf({code:e===$.SERVER_ERROR?e:t||e,params:M({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=wt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Qr?_.href=`ms-settings:privacy-${m[this.functionName]}`:oi&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof D){let{stack:n}=e,a={code:$.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=$.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=$.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=$.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(je.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=$.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=$.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=kS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=$.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=$.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
54
- `)))}else{if(e instanceof o)return e;s=new o({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function kS(o){let i;switch(o){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 V=Rh;function Pi(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Jn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Is(o,i){let e=i?zd:pr;return Il(o)?M(M({},e),o):Qt[o]?Qt[o]:e}var bf={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:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vf={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}}},As={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Nf={name:"userId",required:!0,type:"string"},Df={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Cs(o,i){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Of(o,i,e){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Mf(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new V({code:$.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Lw={type:"number",notLessThanZero:!0},PS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Pf(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Tc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Is(o.option.profile),e=Is(o.option.small,!0);if(!PS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var wS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new V({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Mf(o.roomId,e,i)}else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:As,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:bf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Pf(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(M({},As),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:bf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Pf(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Df},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Df}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:As,publish:{type:"boolean"},option:vf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!_n())throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:As,publish:{type:"boolean"},option:vf}},muteRemoteAudio:[Nf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Nf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:As,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(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Of(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(M({},As),{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(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Of(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new V({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){Cs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!En)throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new V({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Cs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new V({code:$.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new V({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new V({code:$.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Mf(o.roomId,e,i);else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Ge={TRTC:wS};var ut=class extends Error{};function LS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ti(e[t],i[t]);return e}function xS(o){this._resolve=Promise.resolve(o)}function US(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",LS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:xS,reject:US};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(Pr,"instances",new WeakMap);var nr=Pr;var nd=new WeakMap,ad=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new V({code:$.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
55
- `)))}throw i};function wr(o,i){return Y((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(ad.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,h)=>{var g,E;let m=(g=nd.get(this))==null?void 0:g.get(l(...n));if(m){let{timeoutId:C,resolve:k}=m;clearTimeout(C),k()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(ad.bind(null,s)).then(u,h)},c);nd.has(this)?(E=nd.get(this))==null||E.set(l(...n),{timeoutId:_,resolve:u}):nd.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(ad.bind(null,s))})}function Lr(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(ad.bind(null,e)):i.apply(this,t)})}function xr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${ft}/en/TRTC.html#.${i}`;t.warn(r)},e}}var x={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},wf=new Set([x.AUDIO_VOLUME,x.AUDIO_FRAME,x.NETWORK_QUALITY,x.STATISTICS,x.SEI_MESSAGE,x.CUSTOM_MESSAGE,x.LAYER_DATA]);var vh={};Vi(vh,{ScheduleRequestType:()=>Uf,getAbilityConfig:()=>FS,getScheduleDomain:()=>ld,isNeedToSchedule:()=>cd,scheduleProxy:()=>wi,sendScheduleRequest:()=>bh,setIsNeedToSchedule:()=>Lt,setScheduleProxy:()=>dd});var yh=null,xf=0,VS=48*3600*1e3,cd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values($i).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
56
- `));function Lt(o){me(o)&&o!==cd&&(cd=o,R.info(`setIsNeedToSchedule ${o}`),o||(xf=Date.now()+VS))}S.on("28",()=>Lt(!0));S.on("63",()=>Lt(!0));S.on("84",()=>Lt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Lt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Lt(!0)});function BS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Ur(o,"config",p.MAIN),n=Ur(o,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),k=Math.round(a.responseEnd-a.responseStart),ae=[_,g,E,C,k];oe.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${ae.join("->")}) ${c}`,userId:i}),t=L(M({},t),{totalCost:l,local:u,dns:_,tcp:E,tls:g,request:C,response:k});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function bh(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){var h;if(!cd&&yh&&xf>Date.now())return{isCached:!0,result:yh};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(o)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",s),m.append("userSig",String(r));let _=((h=yield Yr())==null?void 0:h.model)||ec();_&&m.append("model",_);let g=ai();g&&m.append("osString",g),a&&m.append("role",String(a)),c&&m.append("latencyLevel",String(c)),n&&m.append("frameWorkType",String(n));let E=U(),C=yield $S(m,u,i);C.config&&(C.config.loggerDomain&&Br(C.config.loggerDomain),me(C.config.scheduleCache)&&Lt(!C.config.scheduleCache)),u.delta=U()-E;let k=BS(Number(i),o,E);return yh=C,{isCached:!1,result:C,detailCost:k}}catch(m){let _=Ae(m)?m[0]:m,g=Q(_.code)?_.code:0,E=`schedule failed${_.message?`: ${_.message}`:""}`,C=new D({code:I.SCHEDULE_FAILED,extraCode:g,message:H({key:B.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),C}})}var wi={main:"",backup:""};function dd(o){Ae(o)?(wi.main=o[0],wi.backup=o[1]):wi.main=o}var Uf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Uf||{});function Ur(o,i,e=p.MAIN,t=!1){return`https://${wi[e]||ld(o,e,t)}/api/v1/${i}`}function FS(o,i,e){let t=Ur(o,i),r=Ur(o,i,p.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return Xr([n,a])}function ld(o,i=p.MAIN,e=!1){let t;return Vt(o)?e?t=i===p.MAIN?$i.MAIN_OVERSEA_BACKUP:$i.BACKUP_OVERSEA:t=i===p.MAIN?$i.MAIN_OVERSEA:$i.BACKUP_OVERSEA:t=i===p.MAIN?$i.MAIN:$i.BACKUP,t}function HS(o,i,e){return new Promise((t,r)=>{Ji({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Lf=(o,i)=>Ci({retryFunction:HS,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function $S(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Lf(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Ur(e,"config",p.MAIN,!0)),a())})(Ur(e,"config",p.MAIN),o,{get timeout(){return qr(2+i.count[0])*1e3}}),Lf(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Ur(e,"config",p.BACKUP,!0)),a())})(Ur(e,"config",p.BACKUP),o,{get timeout(){return qr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var WS=o=>o.startsWith("data:application/octet-stream;base64,"),GS=o=>o.startsWith("file://"),qn=class{constructor(){d(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Oa(i);try{let r=U(),s;if(ue(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=U()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:U()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),v.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=U(),r=null,s=null;if(ue(WebAssembly.instantiateStreaming)&&!WS(i)&&!GS(i)&&ue(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=U()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),v.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=U();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${U()-e}ms`),v.addSuccessEvent({key:522702,cost:U()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),v.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};O([Ot({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],qn.prototype,"download",1),O([Ot({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],qn.prototype,"loadScript",1);var jn=new qn;function Vf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:Xe,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:jn,innerEmitter:S,INNER_EVENT:A,constants:ol,environment:es,utils:Eh,eventLogger:oe,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:v,rtcDectection:vi,trtc:this,rx:gh,enums:Yl,schedule:vh,getDevices:ls,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>f(this,null,function*(){window.VisionTaskRegistry||(yield jn.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Se(),deviceDetector:be,AudioPlayer:hs,showAutoPlayDialog:as,Timer:re,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Gn,createAudioNode:Mn,getNetworkTimeOffset:Em,validateSourceNode:()=>{var r;if(te&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new V({code:$.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var Bf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=H({key:B.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
52
+ } `;var _o=class extends J{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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 Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var SS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",SS),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,TS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,ES),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var Be=_s,Xe=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,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})}};M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function IS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:m,hidden:h}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(m)||(_.layout.rotation=m),T(h)||(_.layout.hidden=h),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Be&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=IS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},O({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Be)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var AS=[1,0,0,0,1,1,0,1],Gt=class extends Ue{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Be)try{this.setTexBuffer(AS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends pi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return p(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var CS=function(o){return p(this,null,function*(){let i=null,e=bS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&qe<74||Re||K)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield RS(r,o.captureElement))}if(o.audio){let s=yS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function RS(o,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function yS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function bS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=CS;var Pt=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):(m=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=m.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof D?m:new D({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};M([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var vS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return p(this,null,function*(){let r=Ee("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([vS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let h=0;h<r.length;h++){let _=URL.createObjectURL(new Blob(n[h])),g=document.createElement("a");g.href=_,g.download=`${r[h]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(h=>h.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,re,P;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),m,h,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(P=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:P.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let A=Ee().createMediaStreamSource(new MediaStream([E]));return Gn([A],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),m=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),h=N[0][1].subarray(c-_)),_+=c-_):(m&&(l.set(m,_),_+=m.length,m=void 0),h&&(u.set(h,_),h=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof gi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof gi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Q((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Q((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ce(this,Mi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new J(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new J(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(Ln(ce(this,J.STATECHANGED),ce(this.remotePublishState,J.STATECHANGED)),Fn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(c=>{this.availableState.state!==(c?J.ON:J.OFF)&&(this.availableState.state=c?J.ON:J.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let s=de(ce(this.player,ue.ERROR),$t(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=de(Un(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===f.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(xu(s,n),ke(ce(this,J.INIT)));de(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===J.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===f.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${si()||ni()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===f.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?J.ON:J.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),M([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),M([ye(J.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),M([ye(Mi.STATE_SUBSCRIBE,J.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var gi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&hi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);de(ce(e,"mousedown"),Bn(this.startDrag.bind(this)),Mr(()=>de(ce(window,"mousemove"),ke(ce(window,"mouseup")))),t,Te(this.doDrag.bind(this))),de(ce(e,"dblclick"),t,Te(this.resetPosition.bind(this))),de(ce(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:m}=u,h=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let A=0;A<g;A++){let k=(E*s+A)*4,re=A+g,P=(E*s+re)*4,Qe=m[P];m[P+3]=0;let N=Qe>=100;m[k+3]=N?255:0}h=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let A=0;A<s;A++){let k=(E*s+A)*4,P=((E+g)*s+A)*4,Qe=m[P];m[P+3]=0;let N=Qe>=100;m[k+3]=N?255:0}h=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&h}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function MS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=MS(t);if(!z(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends Oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ne(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ne(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ne(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ne(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,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&&Ne(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ne(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ne(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===f.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ne(o.userId,e)}});function Ne(o,i){let e=L(O({},i),{timestamp:Fi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).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 Ss.delete(o),i}return[]}function Sf(...o){return Q((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ie(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),le(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Me(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?xo(c):ie(c)?c:Me(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=z(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&z(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&z(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&z(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ie(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=Ge(at(),1);var od=class extends If.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let m=this.remotePublishedUserMap.get(r);m&&m.flag!==s&&(m.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}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:Kt(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.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>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:F.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var kS="2025-12-09 16:57:12",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",He),oi||R.debug("Build Time:",kS);let i=`UA: ${navigator.userAgent}
53
+ CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ti)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var $={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},wt=(y=>(y[y.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",y[y.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",y[y.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",y[y.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",y[y.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",y[y.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",y[y.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",y[y.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",y[y.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",y[y.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",y[y.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",y[y.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",y[y.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",y[y.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",y[y.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",y[y.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",y[y.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",y[y.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",y[y.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",y[y.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",y[y.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",y[y.INVALID_OPERATION=5100]="INVALID_OPERATION",y[y.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",y[y.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",y[y.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",y[y.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",y[y.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",y[y.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",y[y.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",y[y.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",y[y.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",y[y.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",y[y.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",y[y.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",y[y.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",y[y.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",y[y.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",y[y.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",y[y.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",y[y.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",y[y.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",y[y.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",y[y.DEVICE_ERROR=5300]="DEVICE_ERROR",y[y.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",y[y.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",y[y.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",y[y.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",y[y.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",y[y.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",y[y.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",y[y.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",y[y.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",y[y.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",y[y.SERVER_ERROR=5400]="SERVER_ERROR",y[y.NEED_TO_BUY=5401]="NEED_TO_BUY",y[y.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",y[y.OPERATION_FAILED=5500]="OPERATION_FAILED",y[y.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",y[y.REJOIN_FAILED=5502]="REJOIN_FAILED",y[y.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",y[y.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",y[y.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",y[y.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",y[y.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",y[y.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",y[y.OPERATION_ABORT=5998]="OPERATION_ABORT",y[y.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",y))(wt||{});function yf({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=wt[o];try{r=Rf[s]}catch(n){r=Rf.UNKNOWN_ERROR}return le(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Rf=L(O({},Je),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' 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:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' 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:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' 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:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Rh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=yf({code:e===$.SERVER_ERROR?e:t||e,params:O({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=wt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let m={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Qr?_.href=`ms-settings:privacy-${h[this.functionName]}`:ri&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${m[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof D){let{stack:n}=e,a={code:$.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=$.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=$.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=$.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Je.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=$.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=$.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=PS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=$.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=$.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
54
+ `)))}else{if(e instanceof o)return e;s=new o({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function PS(o){let i;switch(o){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 V=Rh;function ki(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function qn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Is(o,i){let e=i?zd:pr;return Il(o)?O(O({},e),o):zt[o]?zt[o]:e}var bf={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:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vf={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}}},As={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Nf={name:"userId",required:!0,type:"string"},Df={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Cs(o,i){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Mf(o,i,e){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Of(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new V({code:$.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Hw={type:"number",notLessThanZero:!0},wS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Pf(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Tc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Is(o.option.profile),e=Is(o.option.small,!0);if(!wS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var LS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new V({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Of(o.roomId,e,i)}else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:As,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:bf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Pf(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:bf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Pf(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Df},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Df}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:As,publish:{type:"boolean"},option:vf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!_n())throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:As,publish:{type:"boolean"},option:vf}},muteRemoteAudio:[Nf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Nf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:As,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(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{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(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new V({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){Cs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!En)throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new V({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Cs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new V({code:$.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new V({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new V({code:$.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Of(o.roomId,e,i);else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},We={TRTC:LS};var ut=class extends Error{};function xS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function US(o){this._resolve=Promise.resolve(o)}function VS(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",xS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:US,reject:VS};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(Pr,"instances",new WeakMap);var nr=Pr;var nd=new WeakMap,ad=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new V({code:$.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
55
+ `)))}throw i};function wr(o,i){return Q((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(ad.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Q((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,m)=>{var g,E;let h=(g=nd.get(this))==null?void 0:g.get(l(...n));if(h){let{timeoutId:A,resolve:k}=h;clearTimeout(A),k()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(ad.bind(null,s)).then(u,m)},c);nd.has(this)?(E=nd.get(this))==null||E.set(l(...n),{timeoutId:_,resolve:u}):nd.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(ad.bind(null,s))})}function Lr(o){return Q((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(ad.bind(null,e)):i.apply(this,t)})}function xr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${ft}/en/TRTC.html#.${i}`;t.warn(r)},e}}var x={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},wf=new Set([x.AUDIO_VOLUME,x.AUDIO_FRAME,x.NETWORK_QUALITY,x.STATISTICS,x.SEI_MESSAGE,x.CUSTOM_MESSAGE,x.LAYER_DATA]);var vh={};Vi(vh,{ScheduleRequestType:()=>Uf,getAbilityConfig:()=>HS,getScheduleDomain:()=>ld,isNeedToSchedule:()=>cd,scheduleProxy:()=>Pi,sendScheduleRequest:()=>bh,setIsNeedToSchedule:()=>Lt,setScheduleProxy:()=>dd});var yh=null,xf=0,FS=48*3600*1e3,cd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values($i).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
56
+ `));function Lt(o){he(o)&&o!==cd&&(cd=o,R.info(`setIsNeedToSchedule ${o}`),o||(xf=Date.now()+FS))}S.on("28",()=>Lt(!0));S.on("63",()=>Lt(!0));S.on("84",()=>Lt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Lt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Lt(!0)});function BS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Ur(o,"config",f.MAIN),n=Ur(o,"config",f.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?f.MAIN:f.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,h=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),A=Math.round(a.responseStart-a.requestStart),k=Math.round(a.responseEnd-a.responseStart),re=[_,g,E,A,k];se.uploadEvent({log:`stat-schedule-net:${l}(${u}(${m}->${h})->${re.join("->")}) ${c}`,userId:i}),t=L(O({},t),{totalCost:l,local:u,dns:_,tcp:E,tls:g,request:A,response:k});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function bh(l){return p(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){var m;if(!cd&&yh&&xf>Date.now())return{isCached:!0,result:yh};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(o)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",s),h.append("userSig",String(r));let _=((m=yield Yr())==null?void 0:m.model)||ec();_&&h.append("model",_);let g=ni();g&&h.append("osString",g),a&&h.append("role",String(a)),c&&h.append("latencyLevel",String(c)),n&&h.append("frameWorkType",String(n));let E=U(),A=yield WS(h,u,i);A.config&&(A.config.loggerDomain&&Fr(A.config.loggerDomain),he(A.config.scheduleCache)&&Lt(!A.config.scheduleCache)),u.delta=U()-E;let k=BS(Number(i),o,E);return yh=A,{isCached:!1,result:A,detailCost:k}}catch(h){let _=Ie(h)?h[0]:h,g=z(_.code)?_.code:0,E=`schedule failed${_.message?`: ${_.message}`:""}`,A=new D({code:I.SCHEDULE_FAILED,extraCode:g,message:H({key:F.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),A}})}var Pi={main:"",backup:""};function dd(o){Ie(o)?(Pi.main=o[0],Pi.backup=o[1]):Pi.main=o}var Uf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Uf||{});function Ur(o,i,e=f.MAIN,t=!1){return`https://${Pi[e]||ld(o,e,t)}/api/v1/${i}`}function HS(o,i,e){let t=Ur(o,i),r=Ur(o,i,f.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return Xr([n,a])}function ld(o,i=f.MAIN,e=!1){let t;return Ut(o)?e?t=i===f.MAIN?$i.MAIN_OVERSEA_BACKUP:$i.BACKUP_OVERSEA:t=i===f.MAIN?$i.MAIN_OVERSEA:$i.BACKUP_OVERSEA:t=i===f.MAIN?$i.MAIN:$i.BACKUP,t}function $S(o,i,e){return new Promise((t,r)=>{qi({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Lf=(o,i)=>Ai({retryFunction:$S,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function WS(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Lf(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Ur(e,"config",f.MAIN,!0)),a())})(Ur(e,"config",f.MAIN),o,{get timeout(){return Jr(2+i.count[0])*1e3}}),Lf(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Ur(e,"config",f.BACKUP,!0)),a())})(Ur(e,"config",f.BACKUP),o,{get timeout(){return Jr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var GS=o=>o.startsWith("data:application/octet-stream;base64,"),qS=o=>o.startsWith("file://"),Jn=class{constructor(){d(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return p(this,null,function*(){let{type:t="blob"}=e||{};i=Ma(i);try{let r=U(),s;if(le(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=U()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:U()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),v.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return p(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return p(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=U(),r=null,s=null;if(le(WebAssembly.instantiateStreaming)&&!GS(i)&&!qS(i)&&le(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=U()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),v.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=U();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${U()-e}ms`),v.addSuccessEvent({key:522702,cost:U()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),v.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};M([Mt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Jn.prototype,"download",1),M([Mt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],Jn.prototype,"loadScript",1);var jn=new Jn;function Nh([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function Dh(o){return o.type==="empty"||o.data.byteLength===0}function Mh(o){let i=new DataView(o),e=0;for(;e<i.byteLength;){let t=0;if(e+4<=i.byteLength&&i.getUint8(e)===0&&i.getUint8(e+1)===0&&i.getUint8(e+2)===0&&i.getUint8(e+3)===1)t=4;else if(e+3<=i.byteLength&&i.getUint8(e)===0&&i.getUint8(e+1)===0&&i.getUint8(e+2)===1)t=3;else{e+=1;continue}let r=e+t;if(r<i.byteLength&&(i.getUint8(r)&31)===6)return!0;let s=-1;for(let n=e+t;n<i.byteLength;n+=1){if(n+4<=i.byteLength&&i.getUint8(n)===0&&i.getUint8(n+1)===0&&i.getUint8(n+2)===0&&i.getUint8(n+3)===1){s=n;break}if(n+3<=i.byteLength&&i.getUint8(n)===0&&i.getUint8(n+1)===0&&i.getUint8(n+2)===1){s=n;break}}e=s===-1?i.byteLength:s}return!1}function Oh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function kh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Oh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Nh),s=r.reduce((u,m)=>u+m.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let m=0;m<r[u].dataView.byteLength;m++)a.setInt8(l++,r[u].dataView.getInt8(m));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Ph({frame:o,onSEI:i}){try{if(Dh(o)||!Mh(o.data))return o;let e=zc(o.data,!1).filter(t=>t.isSEI);i==null||i(e.reverse())}catch(e){}return o}function Vf({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e()})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function Ff({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)):videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:o,streamType:i})})}})}),r.enqueue(s)}})}function ud(o){let i=[sr],e=[Oh,Dh,zc,Mh,Nh,Vf,Ff,Pa,ka],t=()=>{let l=[],u=[],m=[],h=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(l.push(_.data.data),_.data.small&&m.push(_.data.data)):u.push(_.data.data);break;case"ntp-offset":h=_.data.data;break}},self.onrtctransform=_=>{let{options:g}=_.transformer,E=g.isReceiver?Ff({userId:g.userId,streamType:g.streamType,isAudio:g.isAudio}):Vf({getNtpTime:()=>Date.now()+h,isAudio:g.isAudio,isMain:g.isMain,seiMessageList:g.isMain?g.small?m:l:u});_.transformer.readable.pipeThrough(E).pipeTo(_.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
57
+ const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
58
+ const audioEncodePipeline = [${o.audioEncodePipeline.toString()}];
59
+ const audioDecodePipeline = [${o.audioDecodePipeline.toString()}];`,s=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
60
+ `)}
61
+ ${e.map(l=>l.toString()).join(`
62
+ `)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}function Bf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:je,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:jn,innerEmitter:S,INNER_EVENT:C,constants:ol,environment:Ko,utils:Eh,eventLogger:se,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:v,rtcDectection:bi,trtc:this,rx:gh,enums:Yl,schedule:vh,getDevices:ds,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>p(this,null,function*(){window.VisionTaskRegistry||(yield jn.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Ee(),deviceDetector:be,AudioPlayer:us,RemoteAudioPlayer:hs,VideoPlayer:it,showAutoPlayDialog:ns,Timer:oe,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Gn,createAudioNode:On,getNetworkTimeOffset:Em,validateSourceNode:()=>{var r;if(K&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new V({code:$.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:ud}}var Hf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=H({key:F.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
57
63
 
58
- ${r.stack}`),!1}},o};var Rs=new WeakMap;function Ff(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Hf(o,i){return Y((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Wf="trtc-sdk-v5",Nh="5.15.0-beta.2";function st(...o){return Y((i,e)=>function(...t){try{hd.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Dh(...o){return Y((i,e)=>function(...t){try{hd.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function hd(o,i,e,t){if(Ae(o))for(let r=0;r<o.length;r++)ud.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else ud.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function ud({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){ue(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),ue(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Oe(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?Uo(l):ie(l)?l:Oe(l))},value:i}})}else if(!T(o.type)&&Oe(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=Q(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&Q(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&Q(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&Q(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(ue(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{ud.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ae(i)&&i.forEach((c,l)=>{ud.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ue(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ce(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...c){var _,g,E;function l(C,k,ae){if(ae&&ae.includes(C))return"hided";if(e){let w=e(...c);if(c[w.argIndex]===k)return w.value}if(k===c||C in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Oe(k)}`:k instanceof MediaStreamTrack?Ma(k):(JSON.stringify(k),k)}catch(w){return`type:${Oe(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(C,k)=>l(C,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):uc[a],m=(s==null?void 0:s(...c))||!1;try{let C=n.apply(this,c),k=U();if(Tr(C)){let ae=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return C.then(w=>(u.info(`${a}() success ${ae}${i.call(this,...c)}`),v.addSuccessEvent({key:h,cost:U()-k}),w)).catch(w=>{var y;w=V.convertFrom.call(this,w,a,c.length===1?c[0]:c);let Ye=w.extraCode||w.code,N=(y=w.message)!=null&&y.includes(Ye)?"":` code:${Ye}`;throw m||u.error(`${a}() failed ${ae}${i.call(this,...c)} ${w}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:w}),w})}return v.addSuccessEvent({key:h}),C}catch(C){C=V.convertFrom.call(this,C,a);let k=C.extraCode||C.code,ae=(E=C.message)!=null&&E.includes(k)?"":` code:${k}`;throw m||u.error(`${a}() failed ${C}${ae} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:C}),C}})}var md=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ue(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return hd.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var pd=0,Oh,ar=class ar{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Se());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");pd=pd+1,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`created id=${this.getAlias()}${pd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Oh||(Oh=this.doPreload(i)),Oh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return f(this,null,function*(){var m,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:k,timestamp:ae}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,ae,C,k,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:k,timestamp:ae}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,ae,C,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(m=this.localAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield qS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${Do(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var fd=ar;function JS(o,i=p.MAIN){return`https://${wi[i]||ld(o,i)}/api/v1/audioAiAuth`}function qS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Vt(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var _d=0,Mh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new ds(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&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(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)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}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 Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==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 ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var Li=class Li{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);_d=_d+1,this.log=i.log.createChild({id:`${this.getAlias()}${_d}`}),this.log.info(`created id=${this.getAlias()}${_d}`)}getName(){return Li.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Li.startValidateRule;case"update":return Li.updateValidateRule;case"stop":return Li.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Mh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),as()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=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),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(Li,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(Li,"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){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(Li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(Li,"Name","AudioMixer");var gd=Li;var Td=0,kh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Se("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Td=Td+1,this.log=i.log.createChild({id:`${this.getAlias()}${Td}`}),this.log.info(`created id=${this.getAlias()}${Td}`)}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return kh||(kh=this.doPreload(i)),kh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield XS(t,L(M({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.INVALID_PARAMETER,message:l});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:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let _=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[_](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${Do(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}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)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Ed=cr;function XS(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Vt(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${h}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${h}`;break;case 5:_=`Your packages is expired. Refer to: ${h}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${_}`:`${m}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Jf=Je(at(),1);var Ph=class extends Jf.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){oe.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){oe.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},zS=new Ph,wh=zS;function Lh([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function xh(o){return o.type==="empty"||o.data.byteLength===0}function Uh(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function Vh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Bh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Vh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Lh),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Fh({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(xh(o)||!Uh(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new sr(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),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 Bh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Fh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),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:mi?this.encode:Bh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:mi?this.decode:Fh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Sd=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var qf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
64
+ ${r.stack}`),!1}},o};var Rs=new WeakMap;function $f(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Wf(o,i){return Q((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var qf="trtc-sdk-v5",wh="5.15.0-beta.3";function st(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Lh(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function md(o,i,e,t){if(Ie(o))for(let r=0;r<o.length;r++)hd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else hd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function hd({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),le(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?xo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=z(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&z(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&z(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&z(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{hd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ie(i)&&i.forEach((c,l)=>{hd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ae(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Q((n,a)=>function(...c){var _,g,E;function l(A,k,re){if(re&&re.includes(A))return"hided";if(e){let P=e(...c);if(c[P.argIndex]===k)return P.value}if(k===c||A in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Me(k)}`:k instanceof MediaStreamTrack?Oa(k):(JSON.stringify(k),k)}catch(P){return`type:${Me(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(A,k)=>l(A,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let m=t?t(...c):uc[a],h=(s==null?void 0:s(...c))||!1;try{let A=n.apply(this,c),k=U();if(Tr(A)){let re=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return A.then(P=>(u.info(`${a}() success ${re}${i.call(this,...c)}`),v.addSuccessEvent({key:m,cost:U()-k}),P)).catch(P=>{var b;P=V.convertFrom.call(this,P,a,c.length===1?c[0]:c);let Qe=P.extraCode||P.code,N=(b=P.message)!=null&&b.includes(Qe)?"":` code:${Qe}`;throw h||u.error(`${a}() failed ${re}${i.call(this,...c)} ${P}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:P}),P})}return v.addSuccessEvent({key:m}),A}catch(A){A=V.convertFrom.call(this,A,a);let k=A.extraCode||A.code,re=(E=A.message)!=null&&E.includes(k)?"":` code:${k}`;throw h||u.error(`${a}() failed ${A}${re} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:A}),A}})}var pd=o=>Q((i,e)=>function(t,r){return p(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return md.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var fd=0,xh,ar=class ar{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");fd=fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${fd}`}),this.log.info(`created id=${this.getAlias()}${fd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return xh||(xh=this.doPreload(i)),xh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return p(this,null,function*(){var h,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:m=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:A,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,A,k,e)}if(m&&!this.screenAudioWorkletNode){let{sign:A,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,A,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(h=this.localAudioWorkletNode)==null||h.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(A=>{this.customAudioReferenceMap.set(A,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:A,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return p(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return p(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return p(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield jS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var m;let{data:u}=l;switch(u.type){case"cost":let h=(u==null?void 0:u.value)>10?"info":"debug";this.log[h](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${No(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return p(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return p(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var _d=ar;function JS(o,i=f.MAIN){return`https://${Pi[i]||ld(o,i)}/api/v1/audioAiAuth`}function jS(r){return p(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:l};let h=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var gd=0,Uh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new cs(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&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(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)}}reload(i){return p(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}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 Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==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 ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);gd=gd+1,this.log=i.log.createChild({id:`${this.getAlias()}${gd}`}),this.log.info(`created id=${this.getAlias()}${gd}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Uh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return p(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>p(this,null,function*(){return i.play()})});else throw t})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=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),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return p(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(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 r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(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){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(wi,"Name","AudioMixer");var Td=wi;var Ed=0,Vh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Ed=Ed+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ed}`}),this.log.info(`created id=${this.getAlias()}${Ed}`)}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Vh||(Vh=this.doPreload(i)),Vh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield zS(t,L(O({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.INVALID_PARAMETER,message:l});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:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var h;let{data:m}=u;if(m.type==="cost"){let _=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[_](`avg cost: ${m.value} max: ${m==null?void 0:m.max}(${No(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(h=m==null?void 0:m.hist)==null?void 0:h.join(" ")}`)}else m.type==="log"&&this.log[m.logLevel](`${m.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return p(this,null,function*(){this.updateConfig(i)})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Sd=cr;function zS(s,n){return p(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let m=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",h="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${m}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${m}`;break;case 5:_=`Your packages is expired. Refer to: ${m}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${h} Reason: ${c}. ${_}`:`${h}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var jf=Ge(at(),1);var Fh=class extends jf.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},QS=new Fh,Bh=QS;var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),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 kh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ph({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:(e==null?void 0:e.userId)||"",streamType:(e==null?void 0:e.mediaType)===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),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:hi?this.encode:kh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:hi?this.decode:Ph,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Id=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var Xf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
59
65
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
60
66
  2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
61
67
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
62
- 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{qf[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var N0=Object.keys(qf);var QS=0,Id,zn=class zn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++QS}`}),this.log.info("created")}getName(){return zn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return f(this,arguments,function*({visible:i}){i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(Id)yield Id;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Wf}@${$e}/assets/debug-dialog.js`;Id=this._core.fileDownloader.loadScript(e),yield Id}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):$h,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Wh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return $h({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Wh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(zn,"Name","Debug"),d(zn,"autoStart",!0);var Ad=zn;var jf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Cd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=de(e,q.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),le(l,ke(this.stopOB),Ee(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:jf(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),le(l,or(1),ph(Vn))};le(this.startOB,xn(0),Or(a),ke(this.stopOB),Ee(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:jf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},YS={type:"object"},Qn=class Qn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Qn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Qn.Name}getValidateRule(i){return YS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Cd(this.core,t,i);return le(r.trackDoneOB,or(1),Ee(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Cd(this.core,i.track,i))}}};d(Qn,"Name","TRTCAudioDecoder");var Yn=Qn;var Rd=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return ue(this[i])?this[i](e):Promise.reject(new D({code:I.INVALID_PARAMETER,message:H({key:B.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isAvailable){if(l.get(h.userId))return;let m=c.getPCM(_=>{e.emit(x.AUDIO_FRAME,_)},h.userId);l.set(h.userId,m)}});else{if(l.get(r))return;let h=c.getPCM(m=>{e.emit(x.AUDIO_FRAME,m)},r);l.set(r,h)}else if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isSubscribed){let{userId:m}=h,_=l.get(m);_==null||_.abort("disable"),l.delete(m)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause()):s.isAvailable&&s.player.pause():(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(),s.isAvailable&&s.player.pause())});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};O([Sf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Rd.prototype,"enableAudioFrameEvent",1);var Xf=new Rd;var zf=Je(at(),1);var Gh=class extends zf.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Zn=new Gh;var Qf=0,Kn=new Set,Qe=null;Jd(Nh);ts.checkStorage();var J=class J extends Yf.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++Qf}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(M({logger:this._log,frameWorkType:J.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,me(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(gd,t.assetsPath),this._use(fd,t.assetsPath),this._use(Ed,t.assetsPath),this._use(Yn,t.assetsPath),this._use(Ad),t.enableSEI&&En&&this._use(Sd),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(x.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new V({code:$.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Bf(this,"trtc")}static create(e){}static _create(e,t){Cf();let r=new J(e,t||{});return Kn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(x.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(x.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Lt(!0),this._exitRoom().finally(()=>{this.emit(x.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(x.ERROR,V.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(x.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,$s),downlinkRTT:Math.min(e.downlinkRTT,$s)});this.emit(x.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=L(M({},s),{userId:e.userId});r.kind===p.VIDEO&&(n.streamType=Pi(r.streamType)),this.emit(r.kind===p.AUDIO?x.AUDIO_PLAY_STATE_CHANGED:x.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(x.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Le(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(x.SEI_MESSAGE,L(M({},e),{streamType:Pi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,l,u,h;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,$s),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(m.msg_audio_status.uint32_audio_p2p_delay||0)+(m.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:m.msg_audio_status.uint32_audio_cache_ms||0},video:m.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(x.STATISTICS,r)}).add("custom-message",e=>{this.emit(x.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(x.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(x.FIRST_VIDEO_FRAME,L(M({},e),{streamType:Pi(e.streamType)}))}).add("audio-frame",e=>{this.emit(x.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Qe&&Qe.deviceId===Hs){let t=(yield Nr()).find(r=>r.deviceId===Hs);t&&Qe.groupId!==t.groupId&&(Qe=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Nr())[0];if(!t||!Qe||Qe.groupId===t.groupId)return;let r=Qe.deviceId===e.deviceId,s=Qe.deviceId===Hs&&Qe.deviceId===t.deviceId;(r||s)&&(Qe=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Zn).add("permission-state-change",e=>{this.emit(x.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(x.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Bi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Vf.call(this,{TRTC:J,room:this._room,assetsPath:t,errorModule:{RtcError:V,ErrorCode:$,CoreErrorCode:I,ErrorCodeDictionary:wt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return f(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,me(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive,videoProfileLevel:e.videoProfileLevel};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,J.frameWorkType),this._checkTrackToPublish(),wh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof ws&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),Ff(this),this._room.remotePublishedUserMap.forEach(e=>{Le(e.remoteAudioTrack),Le(e.remoteVideoTrack),Le(e.remoteAuxiliaryTrack)})}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(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Le(this),this.removeAllListeners(),this._room.destroy(),Kn.delete(this),Kn.size===0&&wh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},c={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?fa[s.profile]&&n.setProfile(fa[s.profile]):n.setProfile(s.profile)),Q(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),me(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=V.convertFrom(l.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(M({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,L(M({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ti(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Le(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new Xe(this._room.videoManager),l={},u={};a&&(me(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Jn(a.qosPreference)),T(a.profile)||(ie(a.profile)?Qt[a.profile]&&c.setProfile(Qt[a.profile]):c.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),me(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(Is(a.small,!0))),T(a.rotation)||c.setRotation(a.rotation),me(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",m=>{this.emit(x.FIRST_VIDEO_FRAME,L(M({},m),{streamType:Pi(m.streamType)}))}),c.on("5",m=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5308,messageParams:{error:m}}))}),c.on("2",m=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"active",device:m})}),c.on("4",m=>{let _;m.error&&(_=V.convertFrom(m.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(M({},m),{error:_}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(h=c.manager)==null||h.changeInput(c),T(n)||(yield c.setMute(n)),tt(c,c).add("player-state-changed",m=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(M({},m),{userId:"",streamType:"main"}))}).add("video-size-changed",m=>{this.emit(x.VIDEO_SIZE_CHANGED,L(M({},m),{streamType:Pi(m.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=L(M({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:c})})}updateLocalVideo(e){return f(this,null,function*(){var l,u,h;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let m={};m.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),m.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,m.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(m)}a&&(T(a.profile)||(ie(a.profile)?Qt[a.profile]&&this._localVideoTrack.setProfile(Qt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(c.objectFit=a.fillMode),T(a.mirror)||(c.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Jn(a.qosPreference)),T(a.small)||(me(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Is(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ti(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(),Le(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var m,_;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=V.convertFrom(g.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(M({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(x.FIRST_VIDEO_FRAME,L(M({},g),{streamType:Pi(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?_a[n.profile]&&a.setProfile(_a[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Jn(n.qosPreference)));let h=yield a.capture(l);if(a.mediaTrack.addEventListener(p.ENDED,()=>{this._stopScreenShare(),this.emit(x.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]){c=new To(this._room.audioManager);let g=h.getAudioTracks()[0];(m=e.option)!=null&&m.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(c.sourceTrack=g),yield c.setInputMediaStreamTrack(g),me(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(M({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];c&&(g.push(c),this._checkScreenAudioEchoCancellation(a,c)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=L(M({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return f(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Jn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&me(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ti(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;u.on("decode-failed",h=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",h=>{this.emit(x.VIDEO_SIZE_CHANGED,L(M({},h),{streamType:Pi(h.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(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 C,k;let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror));let u=null,h=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(h!=null&&h.muteState.hasVideo)&&(u=h.remoteVideoTrack),s==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:m}=c;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),n&&!T(n.draggable)&&u.setDraggable(n.draggable),yield this._updateVideoPlayOption({view:t,playOption:l,track:u,prevConfig:m}),ti(m,e);let _=T(n==null?void 0:n.receiveWhenViewVisible)?(C=m.option)==null?void 0:C.receiveWhenViewVisible:n.receiveWhenViewVisible,g=T(t)?m.view:t,E=T(n==null?void 0:n.viewRoot)?(k=m.option)==null?void 0:k.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:g,receiveWhenViewVisible:_,viewRoot:E})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==$.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(x.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{wf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===J.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(J.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Nr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Qe=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ft}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Q(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),le(de(n,"decode-failed"),ke(de(n,q.INIT)),Ee(()=>{this.startPlugin(Yn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;le(de(e,"decode-failed"),ke(de(e,q.INIT)),Fn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(de(e,"decode-downgrade-state-changed")),Ee(n=>{s=n.state,this.emit(x.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Vo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ti){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(x.TRACK,{userId:r,streamType:Pi(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:s}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Pi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ae(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(Fo(t));l.forEach((m,_)=>{h.has(_)||(a.unobserve(_),l.delete(_))}),h.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_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 Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Le(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Qe||us(Qe))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Qe&&!us(Qe))this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:Qe});else{let e=yield Nr();e[0]&&!us(e[0])?(Qe=e[0],this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).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 s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(M({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Xf.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return _c(J.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Zn.request(t).catch(a=>{var c;return R.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([Zn.get("camera"),Zn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return Nr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield J.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Kn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Nr()).forEach(r=>{r.deviceId===e&&(Kn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Qe=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:c});break}}};d(J,"VERSION",Nh),d(J,"_loggerManager",R),d(J,"EVENT",x),d(J,"ERROR_CODE",$),d(J,"TYPE",So),d(J,"frameWorkType",30),O([Ce({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],J.prototype,"use",1),O([st(Ge.TRTC.enterRoom),wr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Ce()],J.prototype,"enterRoom",1),O([Ce()],J.prototype,"exitRoom",1),O([st(Ge.TRTC.switchRoom),Ce(),ir()],J.prototype,"switchRoom",1),O([st(Ge.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Ce()],J.prototype,"switchRole",1),O([Ce()],J.prototype,"destroy",1),O([st(Ge.TRTC.startLocalAudio),wr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Ce()],J.prototype,"startLocalAudio",1),O([st(Ge.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${Qf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Ce()],J.prototype,"updateLocalAudio",1),O([Lr("audio"),Ce()],J.prototype,"stopLocalAudio",1),O([st(Ge.TRTC.startLocalVideo),wr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Ce()],J.prototype,"startLocalVideo",1),O([st(Ge.TRTC.updateLocalVideo),Ao("video"),Ce()],J.prototype,"updateLocalVideo",1),O([Lr("video"),Ce()],J.prototype,"stopLocalVideo",1),O([st(Ge.TRTC.startScreenShare),wr("screen",()=>!0),Ce()],J.prototype,"startScreenShare",1),O([st(Ge.TRTC.updateScreenShare),Ao("screen"),Ce()],J.prototype,"updateScreenShare",1),O([Ce()],J.prototype,"stopScreenShare",1),O([st(Ge.TRTC.startRemoteVideo),wr(e=>`v${e.userId}${e.streamType}`,()=>!0),Ce({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"startRemoteVideo",1),O([st(Ge.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Ce({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"updateRemoteVideo",1),O([st(Ge.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Ce({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"stopRemoteVideo",1),O([Lr(e=>`v${e.userId}${e.streamType}`)],J.prototype,"_stopRemoteVideo",1),O([st(...Ge.TRTC.muteRemoteAudio),Ce({getRemoteId:e=>e})],J.prototype,"muteRemoteAudio",1),O([Dh(...Ge.TRTC.setRemoteAudioVolume),Hf(200,e=>e),Ce({getRemoteId:e=>e})],J.prototype,"setRemoteAudioVolume",1),O([md("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),wr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Ce({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],J.prototype,"startPlugin",1),O([md("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ti(e[1],t[1]),e)}),Ce({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>eu[e.getName()]})],J.prototype,"updatePlugin",1),O([md("stop"),Lr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Ce({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>tu[e.getName()]})],J.prototype,"stopPlugin",1),O([Dh(...Ge.TRTC.enableAudioVolumeEvaluation)],J.prototype,"enableAudioVolumeEvaluation",1),O([Ce()],J.prototype,"getVideoSnapshot",1),O([Ce()],J.prototype,"_setCurrentSpeaker",1),O([wr(e=>`a${e.userId}`,()=>!0)],J.prototype,"_startRemoteAudio",1),O([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Lr(e=>`a${e.userId}`)],J.prototype,"_stopRemoteAudio",1),O([Lr("room")],J.prototype,"_exitRoom",1),O([Lr("screen")],J.prototype,"_stopScreenShare",1),O([st(...Ge.TRTC.sendSEIMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],J.prototype,"sendSEIMessage",1),O([st(Ge.TRTC.sendCustomMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],J.prototype,"sendCustomMessage",1),O([xr()],J,"create",1),O([st(Ge.TRTC.create)],J,"_create",1),O([xr()],J,"setLogLevel",1),O([xr()],J,"isSupported",1),O([xr()],J,"getPermissions",1),O([xr()],J,"getCameraList",1),O([xr()],J,"getMicrophoneList",1),O([xr()],J,"getSpeakerList",1);var Jh=J,ea=Jh;var qh=class{constructor(){d(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function ZS(){return f(this,null,function*(){let o,i;try{let _=yield It();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=vi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},h={browser:l.browser,os:l.os,trtc:u,devices:e},m={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};oe.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),oe.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(m)}`,userId:this.userId}),mu()})}function Zf(){return Y(o=>{let i=new qh;return function(e,t,r){return f(this,null,function*(){let s=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 D({code:I.INVALID_OPERATION,message:H({key:B.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new D({code:I.INVALID_OPERATION,message:H({key:B.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(A.JOIN_START,{room:this,roomId:s,params:e});let n=vt.getEnv();n||(n=Fi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ga.OLD_CLOUD_LADDER)?n=Fi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ga.WEBRTC)&&(n=Fi.WEBRTC))),oe.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,ZS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=vt.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&oe.uploadEvent({log:`stat-conv-${Number(si)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var Kf=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function e_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var i_=Je(at());var Ie={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};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,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},t_=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED,qt.RECEIVE_CUSTOM_MSG,qt.UPDATE_NETWORK_TIME_RESULT],G={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var yd=new Set;function r_(o){let i=[...yd.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var eI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],bs=class extends i_.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-yd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,yd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return eI.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=U();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?p.BACKUP:p.MAIN),this._isFirstConnect&&(v.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?p.MAIN:p.BACKUP),c(new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===p.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ie.ONLINE),this.bytesReceived+=Js(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(qt),l=Object.keys(qt)[a.indexOf(s)],u=G[l]||s;switch(t_.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${U()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ie.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:H({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),v.addFailedEvent({key:521701,error:h}),this.emit(Ie.SETUP_FAILED,h)}break}case qt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Lt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?p.MAIN:p.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:G.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:U()-this._connectStartTime}),this._connectStartTime=-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 r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=Js(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let h=()=>{clearTimeout(m),u(new D({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ie.CLOSE,h);let m=setTimeout(()=>{this.off(s,_),this.off(Ie.CLOSE,h);let E=new D({code:I.API_CALL_TIMEOUT,message:H({key:B.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),_=E=>{E.data.seq===g&&(clearTimeout(m),this.off(s,_),this.off(Ie.CLOSE,h),c&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,_);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ci({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ie.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,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),yd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ie.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(G.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(G.JOIN_ROOM_RESULT,t))};this.on(G.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ie.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ie.CONNECTED):e==="DISCONNECTED"&&this.emit(Ie.DISCONNECTED))}};O([Ot({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(v.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],bs.prototype,"connect",1);var o_=Je(at());var jh=0,Xh=!1,bd=new Set,tI=o=>jh>2&&!Xh&&bd.size===0&&o,zh=!1,pt=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new o_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({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=U())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(U()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:U()-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(),bd.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 D({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Yt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Yt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Yt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Yt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Re.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Re.FAILED||i.target.connectionState===Re.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new D({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Re.CONNECTED||i.target.connectionState===Re.COMPLETED)&&(this.logSelectedCandidate(),oe.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jh=0,Xh=!1,zh=!0,bd.add(this)):bd.delete(this),S.emit(A.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(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});jh+=1,tI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xh=!0,this._emitter.emit("firewall-restriction")),e(a)},Fs);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Hi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new D({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:H({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.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(Ie.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};O([Rt(521712,!1)],pt.prototype,"setOffer",1),O([Rt(521713,!1)],pt.prototype,"setAnswer",1);var Kh=Je(Zh());var Ne=function(o){return Kh.default.parse(o)},jt=function(o){return Kh.default.write(o)},h_=function(o){let i=Ne(o);return i.media.forEach(e=>{e.type===p.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),jt(i)};function m_(o){let i=Ne(o);return i.media.forEach(e=>{var t,r;if(e.type===p.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),jt(i)}function vd(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends pt{constructor(e){super(L(M({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ti(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ki(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Es(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Bs?p.MAIN:p.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=p.AUDIO;r.kind===p.VIDEO&&(n=s===p.MAIN?p.VIDEO:p.AUXILIARY);let a=this.remoteAudioTrack;n===p.VIDEO?a=this.remoteVideoTrack:n===p.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
68
+ 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{Xf[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var $x=Object.keys(Xf);var YS=0,Ad,zn=class zn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++YS}`}),this.log.info("created")}getName(){return zn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return p(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return p(this,arguments,function*({visible:i}){i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return p(this,null,function*(){var i;if(!this.dialog)try{if(Ad)yield Ad;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${qf}@${He}/assets/debug-dialog.js`;Ad=this._core.fileDownloader.loadScript(e),yield Ad}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):$h,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Wh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return $h({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Wh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(zn,"Name","Debug"),d(zn,"autoStart",!0);var Cd=zn;var zf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Rd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=ce(e,J.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),de(l,ke(this.stopOB),Te(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:zf(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),de(l,or(1),ph(Vn))};de(this.startOB,xn(0),Mr(a),ke(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:zf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>p(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},ZS={type:"object"},Qn=class Qn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Qn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Qn.Name}getValidateRule(i){return ZS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Rd(this.core,t,i);return de(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Rd(this.core,i.track,i))}}};d(Qn,"Name","TRTCAudioDecoder");var Yn=Qn;var yd=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return p(this,null,function*(){return le(this[i])?this[i](e):Promise.reject(new D({code:I.INVALID_PARAMETER,message:H({key:F.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return p(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let h=c.getPCM(_=>{e.emit(x.AUDIO_FRAME,_)},m.userId);l.set(m.userId,h)}});else{if(l.get(r))return;let m=c.getPCM(h=>{e.emit(x.AUDIO_FRAME,h)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:h}=m,_=l.get(h);_==null||_.abort("disable"),l.delete(h)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return p(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1)):s.isAvailable&&s.player.pause(!1):(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1),s.isAvailable&&s.player.pause(!1))});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}};M([Sf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],yd.prototype,"enableAudioFrameEvent",1);var Qf=new yd;var Yf=Ge(at(),1);var Gh=class extends Yf.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return p(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return p(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Zn=new Gh;var Zf=0,Kn=new Set,ze=null;qd(wh);es.checkStorage();var q=class q extends Kf.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++Zf}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(O({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,he(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Td,t.assetsPath),this._use(_d,t.assetsPath),this._use(Sd,t.assetsPath),this._use(Yn,t.assetsPath),this._use(Cd),t.enableSEI&&En&&this._use(Id),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(x.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new V({code:$.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Hf(this,"trtc")}static create(e){}static _create(e,t){Cf();let r=new q(e,t||{});return Kn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(x.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(x.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Lt(!0),this._exitRoom().finally(()=>{this.emit(x.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(x.ERROR,V.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(x.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(O({},e),{uplinkRTT:Math.min(e.uplinkRTT,$s),downlinkRTT:Math.min(e.downlinkRTT,$s)});this.emit(x.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=L(O({},s),{userId:e.userId});r.kind===f.VIDEO&&(n.streamType=ki(r.streamType)),this.emit(r.kind===f.AUDIO?x.AUDIO_PLAY_STATE_CHANGED:x.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(x.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Le(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(x.SEI_MESSAGE,L(O({},e),{streamType:ki(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,l,u,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,$s),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((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(h=>t[h.uint32_video_stream_type]).map(h=>({bitrate:(h.uint32_video_codec_bitrate||0)/1e3,width:h.uint32_video_width,height:h.uint32_video_height,frameRate:h.uint32_video_enc_fps,videoType:t[h.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(h=>({userId:h.msg_user_info.str_identifier,audio:{bitrate:(h.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(h.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(h.msg_audio_status.uint32_audio_p2p_delay||0)+(h.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:h.msg_audio_status.uint32_audio_cache_ms||0},video:h.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],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(x.STATISTICS,r)}).add("custom-message",e=>{this.emit(x.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(x.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},e),{streamType:ki(e.streamType)}))}).add("audio-frame",e=>{this.emit(x.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ze&&ze.deviceId===Hs){let t=(yield Nr()).find(r=>r.deviceId===Hs);t&&ze.groupId!==t.groupId&&(ze=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Nr())[0];if(!t||!ze||ze.groupId===t.groupId)return;let r=ze.deviceId===e.deviceId,s=ze.deviceId===Hs&&ze.deviceId===t.deviceId;(r||s)&&(ze=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Zn).add("permission-state-change",e=>{this.emit(x.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(x.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Fi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Bf.call(this,{TRTC:q,room:this._room,assetsPath:t,errorModule:{RtcError:V,ErrorCode:$,CoreErrorCode:I,ErrorCodeDictionary:wt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return p(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,he(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),Bh.start()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return p(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof ws&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return p(this,null,function*(){yield this.exitRoom();let t=O(O({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),$f(this),this._room.remotePublishedUserMap.forEach(e=>{Le(e.remoteAudioTrack),Le(e.remoteVideoTrack),Le(e.remoteAuxiliaryTrack)})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Le(this),this.removeAllListeners(),this._room.destroy(),Kn.delete(this),Kn.size===0&&Bh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},c={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&z(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?fa[s.profile]&&n.setProfile(fa[s.profile]):n.setProfile(s.profile)),z(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),he(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=V.convertFrom(l.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,L(O({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(O({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Le(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var m;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new je(this._room.videoManager),l={},u={};a&&(he(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=qn(a.qosPreference)),T(a.profile)||(ie(a.profile)?zt[a.profile]&&c.setProfile(zt[a.profile]):c.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),he(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(Is(a.small,!0))),T(a.rotation)||c.setRotation(a.rotation),he(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",h=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},h),{streamType:ki(h.streamType)}))}),c.on("5",h=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),c.on("2",h=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),c.on("4",h=>{let _;h.error&&(_=V.convertFrom(h.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},h),{error:_}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(m=c.manager)==null||m.changeInput(c),T(n)||(yield c.setMute(n)),tt(c,c).add("player-state-changed",h=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(O({},h),{userId:"",streamType:"main"}))}).add("video-size-changed",h=>{this.emit(x.VIDEO_SIZE_CHANGED,L(O({},h),{streamType:ki(h.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=L(O({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:c})})}updateLocalVideo(e){return p(this,null,function*(){var l,u,m;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let h={};h.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),h.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,h.customSource=(a==null?void 0:a.videoTrack)||((m=this._localVideoConfig.option)==null?void 0:m.videoTrack),yield this._localVideoTrack.capture(h)}a&&(T(a.profile)||(ie(a.profile)?zt[a.profile]&&this._localVideoTrack.setProfile(zt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(c.objectFit=a.fillMode),T(a.mirror)||(c.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(qn(a.qosPreference)),T(a.small)||(he(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Is(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Le(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){var h,_;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=V.convertFrom(g.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},g),{streamType:ki(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?_a[n.profile]&&a.setProfile(_a[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=qn(n.qosPreference)));let m=yield a.capture(l);if(a.mediaTrack.addEventListener(f.ENDED,()=>{this._stopScreenShare(),this.emit(x.SCREEN_SHARE_STOPPED)}),m.getAudioTracks()[0]){c=new To(this._room.audioManager);let g=m.getAudioTracks()[0];(h=e.option)!=null&&h.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(c.sourceTrack=g),yield c.setInputMediaStreamTrack(g),he(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(O({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];c&&(g.push(c),this._checkScreenAudioEchoCancellation(a,c)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=L(O({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return p(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=qn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&he(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;u.on("decode-failed",m=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",m=>{this.emit(x.VIDEO_SIZE_CHANGED,L(O({},m),{streamType:ki(m.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var k,re;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,c=`${r}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror));let m=null,h=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(h!=null&&h.muteState.hasVideo)&&(m=h.remoteVideoTrack),s==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(m=h.remoteAuxiliaryTrack),!m)return;let{config:_}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,m.user),n&&!T(n.draggable)&&m.setDraggable(n.draggable),he(a)&&(m.ignoreUpdatePlayingState=!0,a?(yield m.player.pause(),yield this.room.unsubscribe(m)):(yield this.room.subscribe(m),yield m.player.resume(!0))),yield this._updateVideoPlayOption({view:t,playOption:u,track:m,prevConfig:_}),ei(_,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(k=_.option)==null?void 0:k.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?_.view:t,A=T(n==null?void 0:n.viewRoot)?(re=_.option)==null?void 0:re.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:E,receiveWhenViewVisible:g,viewRoot:A})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return p(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==$.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(x.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{wf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return p(this,null,function*(){(yield Nr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ze=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ft}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=z(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),de(ce(n,"decode-failed"),ke(ce(n,J.INIT)),Te(()=>{this.startPlugin(Yn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;de(ce(e,"decode-failed"),ke(ce(e,J.INIT)),Bn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(ce(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(x.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(O({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Uo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof gi){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(x.TRACK,{userId:r,streamType:ki(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${ki(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ie(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(h=>{h.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let m=new Set(Fo(t));l.forEach((h,_)=>{m.has(_)||(a.unobserve(_),l.delete(_))}),m.forEach(h=>{l.set(h,!0),a.observe(h)}),a.takeRecords().forEach(h=>{l.set(h.target,h.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return p(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Le(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return p(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!ze||ls(ze))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return p(this,null,function*(){if(ze&&!ls(ze))this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze});else{let e=yield Nr();e[0]&&!ls(e[0])?(ze=e[0],this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).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 s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(O({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return p(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Qf.call(e,O({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return _c(q.frameWorkType)}static getPermissions(r){return p(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Zn.request(t).catch(a=>{var c;return R.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([Zn.get("camera"),Zn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return Nr(e)}static setCurrentSpeaker(e){return p(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield q.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Kn.forEach(n=>p(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Nr()).forEach(r=>{r.deviceId===e&&(Kn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ze=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:c});break}}};d(q,"VERSION",wh),d(q,"_loggerManager",R),d(q,"EVENT",x),d(q,"ERROR_CODE",$),d(q,"TYPE",So),d(q,"frameWorkType",30),M([Ae({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],q.prototype,"use",1),M([st(We.TRTC.enterRoom),wr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Q(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Ae()],q.prototype,"enterRoom",1),M([Ae()],q.prototype,"exitRoom",1),M([st(We.TRTC.switchRoom),Ae(),ir()],q.prototype,"switchRoom",1),M([st(We.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Ae()],q.prototype,"switchRole",1),M([Ae()],q.prototype,"destroy",1),M([st(We.TRTC.startLocalAudio),wr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Ae()],q.prototype,"startLocalAudio",1),M([st(We.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${Zf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Ae()],q.prototype,"updateLocalAudio",1),M([Lr("audio"),Ae()],q.prototype,"stopLocalAudio",1),M([st(We.TRTC.startLocalVideo),wr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Ae()],q.prototype,"startLocalVideo",1),M([st(We.TRTC.updateLocalVideo),Ao("video"),Ae()],q.prototype,"updateLocalVideo",1),M([Lr("video"),Ae()],q.prototype,"stopLocalVideo",1),M([st(We.TRTC.startScreenShare),wr("screen",()=>!0),Ae()],q.prototype,"startScreenShare",1),M([st(We.TRTC.updateScreenShare),Ao("screen"),Ae()],q.prototype,"updateScreenShare",1),M([Ae()],q.prototype,"stopScreenShare",1),M([st(We.TRTC.startRemoteVideo),wr(e=>`v${e.userId}${e.streamType}`,()=>!0),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),M([st(We.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),M([st(We.TRTC.stopRemoteVideo),Q(e=>function(t){return p(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),M([Lr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),M([st(...We.TRTC.muteRemoteAudio),Ae({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),M([Lh(...We.TRTC.setRemoteAudioVolume),Wf(200,e=>e),Ae({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),M([pd("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),wr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],q.prototype,"startPlugin",1),M([pd("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ei(e[1],t[1]),e)}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>eu[e.getName()]})],q.prototype,"updatePlugin",1),M([pd("stop"),Lr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>tu[e.getName()]})],q.prototype,"stopPlugin",1),M([Lh(...We.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),M([Ae()],q.prototype,"getVideoSnapshot",1),M([Ae()],q.prototype,"_setCurrentSpeaker",1),M([wr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),M([Q(e=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(O({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Lr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),M([Lr("room")],q.prototype,"_exitRoom",1),M([Lr("screen")],q.prototype,"_stopScreenShare",1),M([st(...We.TRTC.sendSEIMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),M([st(We.TRTC.sendCustomMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),M([xr()],q,"create",1),M([st(We.TRTC.create)],q,"_create",1),M([xr()],q,"setLogLevel",1),M([xr()],q,"isSupported",1),M([xr()],q,"getPermissions",1),M([xr()],q,"getCameraList",1),M([xr()],q,"getMicrophoneList",1),M([xr()],q,"getSpeakerList",1);var qh=q,ea=qh;var Jh=class{constructor(){d(this,"_set",new Set);S.on(C.LEAVE_SUCCESS,this.delete,this),S.on(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function KS(){return p(this,null,function*(){let o,i;try{let _=yield It();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=bi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},m={browser:l.browser,os:l.os,trtc:u,devices:e},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId}),mu()})}function e_(){return Q(o=>{let i=new Jh;return function(e,t,r){return p(this,null,function*(){let s=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 D({code:I.INVALID_OPERATION,message:H({key:F.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new D({code:I.INVALID_OPERATION,message:H({key:F.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(C.JOIN_START,{room:this,roomId:s,params:e});let n=vt.getEnv();n||(n=Bi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ga.OLD_CLOUD_LADDER)?n=Bi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ga.WEBRTC)&&(n=Bi.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),bi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,KS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=vt.performanceNow(),S.emit(C.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(oi)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(C.JOIN_FAILED,{room:this,error:a}),a}})}})}var t_=()=>Q(o=>function(...i){return p(this,null,function*(){S.emit(C.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(C.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function i_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var o_=Ge(at());var Se={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};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,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},r_=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED,qt.RECEIVE_CUSTOM_MSG,qt.UPDATE_NETWORK_TIME_RESULT],G={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Y={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var bd=new Set;function s_(o){let i=[...bd.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var tI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],bs=class extends o_.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-bd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,bd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return tI.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=U();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?f.BACKUP:f.MAIN),this._isFirstConnect&&(v.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?f.MAIN:f.BACKUP),c(new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.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===f.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Se.SETUP_FAILED,new D({code:I.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(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Se.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Se.ONLINE),this.bytesReceived+=qs(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(qt),l=Object.keys(qt)[a.indexOf(s)],u=G[l]||s;switch(r_.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${U()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Se.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let m=new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:H({key:F.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),v.addFailedEvent({key:521701,error:m}),this.emit(Se.SETUP_FAILED,m)}break}case qt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{if(!this.room.joinParams)return;Lt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?f.MAIN:f.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Y.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:G.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:U()-this._connectStartTime}),this._connectStartTime=-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 r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=qs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let m=()=>{clearTimeout(h),u(new D({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Se.CLOSE,m);let h=setTimeout(()=>{this.off(s,_),this.off(Se.CLOSE,m);let E=new D({code:I.API_CALL_TIMEOUT,message:H({key:F.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),_=E=>{E.data.seq===g&&(clearTimeout(h),this.off(s,_),this.off(Se.CLOSE,m),c&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,_);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ai({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Se.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,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),bd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Se.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(G.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(G.JOIN_ROOM_RESULT,t))};this.on(G.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Se.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Se.CONNECTED):e==="DISCONNECTED"&&this.emit(Se.DISCONNECTED))}};M([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(v.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],bs.prototype,"connect",1);var n_=Ge(at());var jh=0,Xh=!1,vd=new Set,iI=o=>jh>2&&!Xh&&vd.size===0&&o,zh=!1,pt=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new n_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({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=U())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(U()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:U()-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(),vd.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 D({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Qt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Qt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Qt}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===Ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Ce.FAILED||i.target.connectionState===Ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new D({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Ce.CONNECTED||i.target.connectionState===Ce.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jh=0,Xh=!1,zh=!0,vd.add(this)):vd.delete(this),S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(C.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});jh+=1,iI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xh=!0,this._emitter.emit("firewall-restriction")),e(a)},Bs);S.on(C.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Se.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Hi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new D({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:H({key:this._isUplink?F.UPLINK_RECONNECTION_FAILED:F.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(Se.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};M([Rt(521712,!1)],pt.prototype,"setOffer",1),M([Rt(521713,!1)],pt.prototype,"setAnswer",1);var Kh=Ge(Zh());var De=function(o){return Kh.default.parse(o)},Jt=function(o){return Kh.default.write(o)},p_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===f.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Jt(i)};function f_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===f.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),Jt(i)}function Nd(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends pt{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new gi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Oi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Es(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}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 Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.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===f.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 s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Fs?f.MAIN:f.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=f.AUDIO;r.kind===f.VIDEO&&(n=s===f.MAIN?f.VIDEO:f.AUXILIARY);let a=this.remoteAudioTrack;n===f.VIDEO?a=this.remoteVideoTrack:n===f.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
63
69
  `),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,c]=s[n];t.splice(a+n,0,c)}return t.join(`\r
64
- `)}addSPSDescription(e){let t=Ne(e);return t.media.forEach(r=>{r.type===p.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),jt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=Ne(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),jt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Re.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Re.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 D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${vd(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:B.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:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Z.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:G.SUBSCRIBE_RESULT,timeout:il});if(!this._peerConnection){let a=new D({code:I.INVALID_OPERATION,message:H({key:B.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};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(p.AUDIO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:se.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield fc();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=m_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=h_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Hr)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new D({code:t,message:H({key:B.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ne(e).media.forEach(r=>{if(r.ssrcs)if(r.type===p.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Bs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Bs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Yd)});s&&(this.ssrc.video=Number(s.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(!(He(Ns.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};O([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ns.prototype,"subscribe",1),O([Rt(521717,!1)],Ns.prototype,"unsubscribe",1),O([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ns.prototype,"connect",1);var em=Ns,tm=em;var f_={voiceActivityDetection:!1},Ds=class Ds extends pt{constructor(e){super(L(M({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||p.AUDIO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?p.VIDEO:c||p.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||p.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||p.VIDEO:p.VIDEO,{direction:se.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(l&&(u[0].sender.track||h.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:p.AUDIO})),c){let m=s?3:1;yield u[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:p.VIDEO,videoType:s?p.AUXILIARY:p.BIG}),h.push(m),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:p.VIDEO,videoType:p.SMALL}),h.push(2))}yield this.setTransceiverDirection(se.SENDONLY,h),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return 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(se.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(se.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!yr()){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 s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(M({},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(se.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._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),bi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===se.INACTIVE&&(yield this.setTransceiverDirection(se.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;yr()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===p.VIDEO&&e instanceof Xe&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Mo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Ne(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===p.VIDEO)return!0;return!1}removeSender(e){let t=null;yr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ue(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
65
- `).map(l=>{if(l.match(new RegExp(`a=(${se.INACTIVE}|${se.RECVONLY}|${se.SENDONLY})`))&&a++,t.includes(a)){if(e===se.INACTIVE&&l.includes(`a=${se.RECVONLY}`))return s=!0,`a=${e}`;if(e===se.SENDONLY&&l.includes(`a=${se.INACTIVE}`))return s=!0,`a=${se.RECVONLY}`}return l}).join(`\r
66
- `);s&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:c}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===p.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===p.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===p.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(St()?r=e.kind===p.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${s?p.AUXILIARY:p.MAIN} stream`),e.kind===p.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===p.VIDEO&&(s?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(f_);te&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let s=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===p.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,state:this._room.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:Z.PUBLISH_CHANGE,data:n,responseCommand:G.UPDATE_OFFER_RESULT,timeout:tl,commandDesc:"update offer"}),{code:c,message:l}=a.data;c!==0&&this.checkPublishResultCode(c,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:s}){if(!Tn())return s?t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,c=this._peerConnection.getSenders();if(St()){let l=0;t===p.VIDEO&&(r===p.SMALL?l=2:r===p.AUXILIARY?l=3:l=1),a=c[l]}else a=c.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,t,r){let s="AS";te&&(s="TIAS",t=t*1e3);let n=0,a=-1;return r===p.SMALL?n=1:r===p.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${s}:${t}\r
67
- `:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return te&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
70
+ `)}addSPSDescription(e){let t=De(e);return t.media.forEach(r=>{r.type===f.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),Jt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=De(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),Jt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Ce.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Ce.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 D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Nd(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:F.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Y.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:G.SUBSCRIBE_RESULT,timeout:il});if(!this._peerConnection){let a=new D({code:I.INVALID_OPERATION,message:H({key:F.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(f.AUDIO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:ne.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield fc();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=f_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=p_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Hr)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new D({code:t,message:H({key:F.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{De(e).media.forEach(r=>{if(r.ssrcs)if(r.type===f.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Fs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Fs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Yd)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return p(this,null,function*(){if(!(Pe(Ns.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Zt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};M([Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ns.prototype,"subscribe",1),M([Rt(521717,!1)],Ns.prototype,"unsubscribe",1),M([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ns.prototype,"connect",1);var em=Ns,tm=em;var g_={voiceActivityDetection:!1},Ds=class Ds extends pt{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||f.AUDIO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?f.VIDEO:c||f.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||f.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||f.VIDEO:f.VIDEO,{direction:ne.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(l&&(u[0].sender.track||m.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:f.AUDIO})),c){let h=s?3:1;yield u[h].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:f.VIDEO,videoType:s?f.AUXILIARY:f.BIG}),m.push(h),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:f.VIDEO,videoType:f.SMALL}),m.push(2))}yield this.setTransceiverDirection(ne.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(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ne.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ne.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!yr()){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 s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},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(ne.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),yi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?f.AUXILIARY:f.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;yr()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===f.VIDEO&&e instanceof je&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Mo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=De(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===f.VIDEO)return!0;return!1}removeSender(e){let t=null;yr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&le(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?f.AUXILIARY:f.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!K)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
71
+ `).map(l=>{if(l.match(new RegExp(`a=(${ne.INACTIVE}|${ne.RECVONLY}|${ne.SENDONLY})`))&&a++,t.includes(a)){if(e===ne.INACTIVE&&l.includes(`a=${ne.RECVONLY}`))return s=!0,`a=${e}`;if(e===ne.SENDONLY&&l.includes(`a=${ne.INACTIVE}`))return s=!0,`a=${ne.RECVONLY}`}return l}).join(`\r
72
+ `);s&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:c}))})}removeTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===f.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===f.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===f.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(St()?r=e.kind===f.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${s?f.AUXILIARY:f.MAIN} stream`),e.kind===f.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===f.VIDEO&&(s?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return p(this,null,function*(){try{let r=yield this._peerConnection.createOffer(g_);K&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let s=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===f.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,state:this._room.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:Y.PUBLISH_CHANGE,data:n,responseCommand:G.UPDATE_OFFER_RESULT,timeout:tl,commandDesc:"update offer"}),{code:c,message:l}=a.data;c!==0&&this.checkPublishResultCode(c,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:s}){if(!Tn())return s?t===f.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,c=this._peerConnection.getSenders();if(St()){let l=0;t===f.VIDEO&&(r===f.SMALL?l=2:r===f.AUXILIARY?l=3:l=1),a=c[l]}else a=c.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return t===f.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,t,r){let s="AS";K&&(s="TIAS",t=t*1e3);let n=0,a=-1;return r===f.SMALL?n=1:r===f.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${s}:${t}\r
73
+ `:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return K&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
68
74
  c=IN $2\r
69
75
  b=${r}:${t}\r
70
- `),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(f_);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Z.PUBLISH,responseCommand:G.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Pt||this.localAuxVideoTrack instanceof Pt,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:s,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,s)})}setSDPDirection(e,t,r="all"){let s=Ne(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),jt(s)}acceptAnswer(e){return f(this,null,function*(){var t,r,s,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),m=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(h){let _=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:h,type:p.VIDEO,sdp:c,videoType:_})}m&&(c=yield this.setBandwidth({bandwidth:m,type:p.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:p.VIDEO,videoType:p.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this.setAnswer(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.send(Z.UPDATE_MUTE_STAT,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(He(Ds.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,responseCommand:G.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ne(e).media.forEach((r,s)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Mo&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(s){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}};O([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ds.prototype,"publish",1),O([Rt(521715,!1)],Ds.prototype,"unpublish",1),O([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ds.prototype,"connect",1);var im=Ds,ia=im;var ra=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"_decodeMap",new Map);d(this,"_prevQpSum",0);d(this,"_prevAuxQpSum",0);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,h,m,_,g,E,C,k,ae,w,Ye,N,y;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(c=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=p.AUXILIARY),!c)return;e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay);let ge=0;if(!T(a.qpSum)&&!T(a.framesEncoded)&&a.framesEncoded>0){let ce=a.qpSum,De=a.framesEncoded,Ut=c===p.VIDEO?this._prevQpSum:this._prevAuxQpSum,No=c===p.VIDEO?((h=(u=i.localMainVideoTrack)==null?void 0:u.stat)==null?void 0:h.framesEncoded)||0:((_=(m=i.localAuxVideoTrack)==null?void 0:m.stat)==null?void 0:_.framesEncoded)||0;if(De>No&&ce>Ut){let Bd=ce-Ut,Fd=De-No;ge=Math.round(Bd/Fd),ge>35&&this._log.warn(`${c===p.AUXILIARY?"aux ":""}video encoder QP is high: ${ge}, resolution: ${a.frameWidth}x${a.frameHeight}, codec: ${i.videoCodec}, `)}c===p.VIDEO?this._prevQpSum=ce:c===p.AUXILIARY&&(this._prevAuxQpSum=ce)}if(!T(a.encoderImplementation)&&(c===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let ce=2,De=this._prevEncoderImplementation;c===p.AUXILIARY&&(ce=7,De=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:ce,prevImplementation:De,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(g=i.localMainVideoTrack)==null?void 0:g.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(E=i.localAuxVideoTrack)==null?void 0:E.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else if(a.type==="candidate-pair")Cr(a)&&(this.totalBytesSent=a.bytesSent,Q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)));else if(a.type==="media-source"){if(a.kind===p.AUDIO)e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,T((ae=(k=(C=i.localMainAudioTrack)==null?void 0:C.sourceTrack)==null?void 0:k.stats)==null?void 0:ae.deliveredFramesDuration)?a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration):e.audio.totalSamplesDuration=i.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(a.kind===p.VIDEO)if(a.trackIdentifier===i.getVideoTrackId(p.VIDEO))if((N=(Ye=(w=i.localMainVideoTrack)==null?void 0:w.sourceTrack)==null?void 0:Ye.stats)!=null&&N.deliveredFrames){let{deliveredFrames:j}=i.localMainVideoTrack.sourceTrack.stats;e.video.framesCaptured=j,i.localMainVideoTrack.stat.framesCaptured&&i.localMainVideoTrack.stat.framesCaptured>0&&j>=i.localMainVideoTrack.stat.framesCaptured?e.video.fpsCapture=Math.floor((j-i.localMainVideoTrack.stat.framesCaptured)/this.statInterval):e.video.fpsCapture=a.framesPerSecond}else e.video.fpsCapture=a.framesPerSecond;else a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond}if(!T(a.audioLevel)&&((y=i.localMainAudioTrack)!=null&&y.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let j=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?j=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(j=p.AUXILIARY),e[j].frameWidth=a.frameWidth,e[j].frameHeight=a.frameHeight,e[j].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel(),c=i.localMainAudioTrack.getInternalAudioLevelAfter3A();e.audio.audioCaptureEnergyAfter3a=c,e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=c!=null?c:a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,s,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{var m,_;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let g=(h.mediaType||h.kind)===p.AUDIO;if(g){if(h.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=h.packetsReceived,e.audio.bytesReceived=h.bytesReceived,e.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(e.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(e.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(e.audio.concealedSamples=h.concealedSamples),h.silentConcealedSamples&&(e.audio.silentConcealedSamples=h.silentConcealedSamples);let{remoteAudioTrack:E}=i;E.stat.packetsReceived=h.packetsReceived,E.stat.bytesReceived=h.bytesReceived,E.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=E.stat.end2EndDelay,e.hasAudio=!0}else{if(te&&h.bytesReceived===0)return;let E;h.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=h.packetsReceived,e.video.bytesReceived=h.bytesReceived,e.video.packetsLost=h.packetsLost,e.video.framesReceived=h.framesReceived,e.video.framesDecoded=h.framesDecoded,e.video.fpsDecoded=h.framesPerSecond,e.hasVideo=!0,i.videoCodec=Ht[(m=this._decodeMap.get(h.codecId))==null?void 0:m.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,E=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==h.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${h.decoderImplementation}(${i.videoCodec}) HWDecoder: ${h.powerEfficientDecoder}`),S.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:h.decoderImplementation,codec:i.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,h.decoderImplementation))),h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=h.packetsReceived,e.auxiliary.bytesReceived=h.bytesReceived,e.auxiliary.packetsLost=h.packetsLost,e.auxiliary.framesReceived=h.framesReceived,e.auxiliary.framesDecoded=h.framesDecoded,e.auxiliary.fpsDecoded=h.framesPerSecond,E=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=E.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((_=this._decodeMap.get(h.codecId))==null?void 0:_.mimeType.split("/")[1].toLowerCase())||"h264"),E&&(E.stat.packetsReceived=h.packetsReceived,E.stat.bytesReceived=h.bytesReceived,E.stat.packetsLost=h.packetsLost,E.stat.framesReceived=h.framesReceived,E.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(E.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=E.stat.end2EndDelay)}h.jitterBufferDelay&&(g?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&Cr(h)&&(this.totalBytesReceived=h.bytesReceived,Q(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));T(h.frameWidth)||((h.trackIdentifier===i.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(e.video.frameWidth=h.frameWidth,e.video.frameHeight=h.frameHeight,i.remoteVideoTrack.stat.frameWidth=h.frameWidth,i.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===i.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=h.frameWidth,e.auxiliary.frameHeight=h.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!T(h.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&h.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=h.audioLevel||0,e.audio.totalAudioEnergy=h.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((s=i.remoteAuxiliaryTrack.player.stat)==null?void 0:s.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r,s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let a=U(),c=yield n.getStats(),l=U();l-a>2e3&&this._log.warn(`getStats cost ${l-a}ms`);let u=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);c.forEach(m=>h.has(m.type)&&u.push(m)),this._spcStats=u}i&&(t=yield this.getSenderStats(i));for(let[n,a]of e){let c=yield this.getReceiverStats(a);s.push(c)}return e.size&&(r=this.getMediaPlayoutStats(this._spcStats)),{senderStats:t,receiverStats:s,mediaPlayoutStats:r}})}getDifferenceValue(i,e){if(_i(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t,uplinkConnection:r}){var m,_,g,E,C,k,ae,w,Ye;if(!_i(i.senderStats)){let N={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&&(N.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Dt),T(i.senderStats.audio.audioCaptureEnergyAfter3a)||(N.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let y=[];if(i.senderStats.video.bytesSent){let ge={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};y.push(ge)}if(i.senderStats.small.bytesSent){let ge={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};y.push(ge)}if(i.senderStats.auxiliary.bytesSent){let ge={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};y.push(ge)}let j={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:N,msg_video_status:y,msg_network_status:j}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(N=>{let y={msg_user_info:{str_identifier:N.userId,uint64_tinyid:N.tinyId},msg_network_status:{uint32_rtt:N.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(N.hasAudio){let j={uint32_audio_p2p_delay:N.audio.p2pDelay,uint32_audio_cache_ms:N.audio.totalJitter,uint32_audio_cache_ms_count:N.audio.totalJitterCount,uint32_audio_codec_bitrate:N.audio.bytesReceived,uint32_audio_total_bitrate:N.audio.bytesReceived,uint32_audio_level:N.audio.audioLevel*1e8,uint32_audio_energy:N.audio.totalAudioEnergy*1e6,uint32_audio_receive:N.audio.packetsReceived,uint32_audio_origin_lost:N.audio.packetsLost};y.msg_audio_status=j}if(N.hasVideo){let j=t.get(`${N.userId}_${Zd}`),ge=j?j.duration:0,ce={uint32_video_stream_type:N.isSmallSubscribed?3:2,uint32_video_receive_fps:N.video.framesReceived,uint32_video_width:N.video.frameWidth,uint32_video_height:N.video.frameHeight,uint32_video_codec_bitrate:N.video.bytesReceived,uint32_video_receive:N.video.packetsReceived,uint32_video_origin_lost:N.video.packetsLost,uint32_video_block_time:ge,uint32_video_dec_fps:N.video.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.video.totalJitter,uint32_video_cache_ms_count:N.video.totalJitterCount,uint32_video_p2p_delay:N.video.p2pDelay,uint32_video_codec:N.video.codec};y.msg_video_status.push(ce)}if(N.hasAuxiliary){let j=t.get(`${N.userId}_${Kd}`),ge=j?j.duration:0,ce={uint32_video_stream_type:7,uint32_video_receive_fps:N.auxiliary.framesReceived,uint32_video_width:N.auxiliary.frameWidth,uint32_video_height:N.auxiliary.frameHeight,uint32_video_codec_bitrate:N.auxiliary.bytesReceived,uint32_video_receive:N.auxiliary.packetsReceived+N.auxiliary.packetsLost,uint32_video_origin_lost:N.auxiliary.packetsLost,uint32_video_block_time:ge,uint32_video_dec_fps:N.auxiliary.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.auxiliary.totalJitter,uint32_video_cache_ms_count:N.auxiliary.totalJitterCount,uint32_video_p2p_delay:N.auxiliary.p2pDelay,uint32_video_codec:N.video.codec};y.msg_video_status.push(ce)}e.msg_down_stream_info.push(y)}),i.mediaPlayoutStats&&!_i(i.mediaPlayoutStats)&&(i.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,i.mediaPlayoutStats.totalSamplesDuration*=1e3);let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let N=n.msg_up_stream_info.msg_audio_status,y=e.msg_up_stream_info.msg_audio_status;if(N.uint32_audio_codec_bitrate===0)y.uint32_audio_codec_bitrate=0;else{let j=this.getDifferenceValue(N.uint32_audio_codec_bitrate,y.uint32_audio_codec_bitrate);y.uint32_audio_codec_bitrate=Math.round(j*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=y.uint32_audio_codec_bitrate}(m=n.msg_device_info)!=null&&m.uint32_audio_capture_cost?(e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s),e.msg_device_info.uint32_audio_capture_cost>0&&((g=r==null?void 0:r.localMainAudioTrack)==null||g.updateAfter3aSilenceStartTime((_=i.senderStats.audio.audioCaptureEnergyAfter3a)!=null?_:i.senderStats.audio.micAudioLevel))):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(N=>{let y=c.find(Ut=>Ut.uint32_video_stream_type===N.uint32_video_stream_type);if(!y||y.uint32_video_codec_bitrate===0){N.uint32_video_codec_bitrate=0,N.uint32_video_enc_fps=0,N.uint32_video_codec_fps=0;return}let j=0,ge=0,ce=0;y&&N.uint32_video_codec_bitrate>=y.uint32_video_codec_bitrate&&(j=y.uint32_video_codec_bitrate,ge=y.uint32_video_enc_fps,ce=y.uint32_video_codec_fps);let De=this.getDifferenceValue(j,N.uint32_video_codec_bitrate);N.uint32_video_codec_bitrate=Math.round(De*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=N.uint32_video_codec_bitrate,N.uint32_video_enc_fps=Math.round(this.getDifferenceValue(ge,N.uint32_video_enc_fps)/s),N.uint32_video_codec_fps=Math.round(this.getDifferenceValue(ce,N.uint32_video_codec_fps)/s),y.uint32_video_width===0&&y.uint32_video_height===0&&y.uint32_video_codec_fps===0&&(N.uint32_video_codec_fps=N.uint32_video_enc_fps),T(y.uint32_key_frame_count)||(N.uint32_key_frame_count=Math.round(this.getDifferenceValue(y.uint32_key_frame_count,N.uint32_key_frame_count))),T(y.uint32_nack_count)||(N.uint32_nack_count=Math.round(this.getDifferenceValue(y.uint32_nack_count,N.uint32_nack_count))),T(y.uint32_pli_count)||(N.uint32_pli_count=Math.round(this.getDifferenceValue(y.uint32_pli_count,N.uint32_pli_count))),T(y.uint32_video_arq_packets)||(N.uint32_video_arq_packets=Math.round(this.getDifferenceValue(y.uint32_video_arq_packets,N.uint32_video_arq_packets))),T(y.uint32_encode_cost)||(N.uint32_encode_cost=Math.round(this.getDifferenceValue(y.uint32_encode_cost,N.uint32_encode_cost)/s)),T(y.uint32_send_packet_cost)||(N.uint32_send_packet_cost=Math.round(this.getDifferenceValue(y.uint32_send_packet_cost,N.uint32_send_packet_cost)/s))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(N=>u.find(y=>y.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;if(h.forEach(N=>{let y=u.find(j=>j.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid);if(!_i(N.msg_audio_status)&&!_i(y.msg_audio_status)){let j=N.msg_audio_status,ge=y.msg_audio_status,ce=this.getDifferenceValue(ge.uint32_audio_cache_ms_count,j.uint32_audio_cache_ms_count);delete j.uint32_audio_cache_ms_count,j.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(ge.uint32_audio_cache_ms,j.uint32_audio_cache_ms)/ce)||0;let De=this.room.remotePublishedUserMap.get(N.msg_user_info.str_identifier);De&&(De.remoteAudioTrack.stat.jitterBufferDelay=j.uint32_audio_cache_ms),j.uint32_audio_origin_lost=this.getDifferenceValue(ge.uint32_audio_origin_lost,j.uint32_audio_origin_lost),j.uint32_audio_receive=this.getDifferenceValue(ge.uint32_audio_receive,j.uint32_audio_receive),j.uint32_audio_receive+=j.uint32_audio_origin_lost;let Ut=this.getDifferenceValue(ge.uint32_audio_codec_bitrate,j.uint32_audio_codec_bitrate);j.uint32_audio_codec_bitrate=Math.round(Ut*8/s),j.uint32_audio_total_bitrate=Math.round(Ut*8/s)}else N.msg_audio_status={};if(N.msg_video_status&&y.msg_video_status){let j=y.msg_video_status;N.msg_video_status=N.msg_video_status.filter(ce=>j.find(De=>De.uint32_video_stream_type===ce.uint32_video_stream_type)),N.msg_video_status.forEach(ce=>{let De=j.find(Q_=>Q_.uint32_video_stream_type===ce.uint32_video_stream_type),Ut=De.uint32_video_receive,No=De.uint32_video_origin_lost,Bd=De.uint32_video_codec_bitrate,Fd=De.uint32_video_receive_fps,j_=De.uint32_video_dec_fps;ce.uint32_video_origin_lost=this.getDifferenceValue(No,ce.uint32_video_origin_lost),ce.uint32_video_receive=this.getDifferenceValue(Ut,ce.uint32_video_receive)+ce.uint32_video_origin_lost;let X_=this.getDifferenceValue(Bd,ce.uint32_video_codec_bitrate);ce.uint32_video_codec_bitrate=Math.round(X_*8/s);let z_=this.getDifferenceValue(Fd,ce.uint32_video_receive_fps);ce.uint32_video_receive_fps=Math.round(z_/s),ce.uint32_video_dec_fps=Math.round(this.getDifferenceValue(j_,ce.uint32_video_dec_fps)/s);let F=this.getDifferenceValue(De.uint32_video_cache_ms_count,ce.uint32_video_cache_ms_count);delete ce.uint32_video_cache_ms_count,ce.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(De.uint32_video_cache_ms,ce.uint32_video_cache_ms)/F)||0})}}),!T((E=a==null?void 0:a.mediaPlayoutStats)==null?void 0:E.totalSamplesDuration)&&!T((C=i.mediaPlayoutStats)==null?void 0:C.totalSamplesDuration)){let N=2*Math.floor(this.getDifferenceValue((k=a==null?void 0:a.mediaPlayoutStats)==null?void 0:k.synthesizedSamplesDuration,(ae=i.mediaPlayoutStats)==null?void 0:ae.synthesizedSamplesDuration)/s),y=2*Math.floor(this.getDifferenceValue((w=a==null?void 0:a.mediaPlayoutStats)==null?void 0:w.totalSamplesDuration,(Ye=i.mediaPlayoutStats)==null?void 0:Ye.totalSamplesDuration)/s);e.msg_device_info.uint32_audio_play_cost=y-N}return a&&i.receiverStats.forEach(N=>{if(N.audio.concealedSamples&&N.audio.totalSamplesReceived){let y=a.receiverStats.find(j=>j.userId===N.userId);if(y&&y.audio.concealedSamples&&y.audio.totalSamplesReceived){let j=(N.audio.silentConcealedSamples||0)-(y.audio.silentConcealedSamples||0),ge=N.audio.concealedSamples-y.audio.concealedSamples,ce=N.audio.totalSamplesReceived-y.audio.totalSamplesReceived,De=Math.floor((ge-j)/ce*1e3*s);if(De>s*1e3/5){let Ut=h.find(No=>No.msg_user_info.str_identifier===N.userId);Ut&&(Ut.msg_audio_status.uint32_audio_block_time=De)}}}}),e.msg_down_stream_info.forEach(N=>{N.msg_video_status.forEach(y=>{y.uint32_video_codec_bitrate===0&&y.uint32_video_receive_fps===0&&(y.uint32_video_width=0,y.uint32_video_height=0)})}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let s={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,uint32_audio_capture_energy_after3a: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(s))),this.prepareReport({stats:n,report:s,freezeMap:t,uplinkConnection:i}),this._prevReportTime=Date.now(),s})}getMediaPlayoutStats(i){let e;if(Ae(i)){for(let t of i)if(t.type==="media-playout"){let{synthesizedSamplesDuration:r,totalSamplesDuration:s}=t;e={synthesizedSamplesDuration:r,totalSamplesDuration:s};break}return e}}reset(){var i;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,(i=this.room.localMainVideoTrack)!=null&&i.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}};var T_=Je(at());function __(o){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===o){let r=Math.round(t.duration),s=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),h=Math.round(t.responseStart-t.requestStart),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(M({},i),{totalCost:r,local:s,redirect:n,httpCache:a,dns:c,tcp:u,tls:l,request:h,response:m});break}}catch(e){}return i}function g_(o){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${o}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let s=__(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var uI=700,Ro=class Ro extends T_.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=R.createLogger({parent:t.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(G.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ie.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let s=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=s-n;s===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/s*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)===Re.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:h}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:h});continue}let m=0,_=this._downlinkPrevStatMap.get(c),g=u-_.totalPacketsLost,E=h-_.totalPacketsReceived;g<=0||E<0?m=0:m=Math.round(g/(g+E)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:s,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,s)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!oo())return t;let r=e.getReceivers();try{for(let s=0;s<r.length;s++)(yield r[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&Q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===p.AUDIO||c.mediaType===p.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(s){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===Re.DISCONNECTED||e.connectionState===Re.FAILED||e.connectionState===Re.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=re.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];S.emit(A.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(M({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Ro.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-Ro.lastPingTime>t.interval*1e3){Ro.lastPingTime=Date.now();let a=t.domain.map(c=>g_(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>uI),this.pingResults.timestamp=s,this.pingResults.data=c,c.forEach(l=>{v.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:s,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:n})}})}};d(Ro,"EVENT_NETWORK_QUALITY","0"),d(Ro,"lastPingTime",0);var Os=Ro;function hI({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return Tr(t)?t.catch(r=>R.error(`${o.name}() error observed ${r}`)):t}catch(t){R.error(`${o.name}() error observed ${t}`)}}}var Nd=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=R.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ue(this[e])&&(this[e]=hI({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:$e,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,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Yr().then(()=>{this._basicInfo.string_os_version=ai(),this._basicInfo.string_device_name=ni()||this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),S.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(A.JOIN_START,this.handleJoinStart).addEvent(A.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(A.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(A.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(A.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(A.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(A.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(A.JOIN_FAILED,this.handleJoinFailed).addEvent(A.LEAVE_START,this.handleLeaveStart).addEvent(A.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(A.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(A.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(A.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(A.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(A.PUBLISH_START,this.handlePublishStart).addEvent(A.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(A.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(A.PLAY_TRACK_START,this.handlePlayStart).addEvent(A.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(A.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(A.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(A.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(A.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(A.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(A.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(A.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>S.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:s,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.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){var e;if(this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0){if(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;let t=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;t&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=U()-t)}else 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())}handleSwitchRoomStart(i){if(this.hitTest(i.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:i}){if(this.hitTest(i)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let s={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:L(M({},mI),{msg_user_info:new oa({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,s)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:s,tinyId:n,role:a}=e,c=new oa({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${s}_${t}`,h=this._remoteStreamStatMap.get(u);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.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:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,s=this._remoteStreamStatMap.get(r);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,v.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,u,h;s&&(l=s,u=1),n&&(c=n,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:h,videoDelayCount:u})}}))}handleHeartbeatStats(i){var e;if(this.hitTest(i.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:s}=i.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:n}=r.msg_audio_status;Math.floor(n/Dt*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Dt,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:c,msg_video_status:l}=n,u=a.str_identifier,h=this._room.remotePublishedUserMap.get(u);if(l.forEach(m=>{let _=m.uint32_video_stream_type===2,g=m.uint32_video_stream_type===7,E=`${u}_${_?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(E);if(C&&(_&&(h!=null&&h.remoteVideoTrack.isSubscribed)||g&&(h!=null&&h.remoteAuxiliaryTrack))){C.totalVideoFPS+=m.uint32_video_receive_fps,C.totalVideoBitrate+=m.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=m.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=m.uint32_video_height);let k=_?h.remoteVideoTrack:h.remoteAuxiliaryTrack;k.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=k.stat.jitterBufferDelay),k.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(k.stat.framesDecoded/k.stat.framesReceived*hr(10,6)))}}),!Vo(c)){let m=`${u}_main`,_=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&_&&h!=null&&h.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/Dt*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/Dt,_.audioLevelCount++),c.uint32_audio_block_time&&(_.statsToReport.uint32_audio_block_time+=c.uint32_audio_block_time))}}),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.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)),t.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof D?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&fr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&_r)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Fr)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:h,audioDelayCount:m,videoDelayCount:_,totalAudioDelay:g,totalVideoDelay:E}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),m&&g&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(g/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&E&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(E/_))}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:s}=this._room;s&&(i.statsToReport.uint32_audio_play_time=s.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=s.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,yo));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_audio_block_time=Math.min(i.statsToReport.uint32_audio_block_time,i.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>yo&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),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>yo&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>yo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+yo)}getReportData(){this._basicInfo.uint32_networkType=Jr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new oa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Bo(this._signalInfo.relayIp),uint32_client_ip:Bo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*hr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Bo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return qs(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=Ir.enable?Gi(i,2001,e):yield El(i),r=t instanceof ArrayBuffer,s=`${Wi(e,mr.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t));let a=[this.uploadKVStat(v),this.uploadKVStat(ro)];n||a.push(Ji({url:s,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(M({},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=Ir.enable?Gi(e,2003,this._room.sdkAppId):yield El(e),r=t instanceof ArrayBuffer,s=`${Wi(+this._room.sdkAppId,mr.KV_STAT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Ji({url:s,body:t})})}};O([Ot({settings:{timeout:500,retries:3}})],Nd.prototype,"upload",1);var yo=5e3,mI={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},oa=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},E_=Nd;var rm=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=U())}stop(){this._endTime===0&&(this._endTime=U())}getDuration(){return this._endTime===0?U()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Dd=rm;var om=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(A.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(A.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);s&&(!e.hasAudio&&t.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,s=new Dd,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[s]:[],video:e===p.AUDIO?[]:[s]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(s=>s.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,s)=>r+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},S_=om;var sm=class{constructor(){d(this,"renderFreezeMap",new Map);d(this,"dataFreezeMap",new Map)}get(i,e){let t=this.renderFreezeMap.get(i),r=this.dataFreezeMap.get(i);return e?e==="data"?r:t:(Pe||te)&&t&&r&&t.duration>r.duration?t:r}set(i,e,t){t==="data"?this.dataFreezeMap.set(i,e):this.renderFreezeMap.set(i,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},nm=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new sm);d(this,"_eventMap",new Map);d(this,"_videoEncodeFailedCount",0);d(this,"_audioEncodeFailedCount",0);d(this,"_encodeFailedThreshold",3);d(this,"eventListenerMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(A.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(A.PLAY_TRACK_START,this.onPlayTrackStart).set(A.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,s=`${r}_${e}`;this.stopDataFreeze({key:s,userId:r,type:e})}).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let s="main",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}if(e.hasAuxiliary&&!t.hasAuxiliary){let s="auxiliary",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}}).set(A.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let s=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(A.HEARTBEAT_REPORT,this.onHearBeatReport).set(A.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(A.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,s=this._dataFreezeMap.get(r),n=new Dd;s?s.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){if(this.hitTest(i)){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0||r!=null&&r.isUseCustomSource)return;t.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(r!=null&&r.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&oe.uploadEvent({userId:this._room.userId,log:`stat-${Ze.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&oe.uploadEvent({userId:this._room.userId,log:`stat-${Ze.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let s=r.durationItemList[r.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Sa){let a=this._monitorFreezeData.get(i,"data");this._monitorFreezeData.set(i,{userId:e,type:t,duration:a?a.duration+n:n},"data")}else r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Sa&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e={renderFreeze:0,count:0},t=this._renderFreezeMap.get(i);return t&&(e.renderFreeze=t.totalDuration,e.count=t.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}onRemoteVideoPlayStart({track:i,player:e}){var n;if(!Ki())return;let t=0,r=()=>{document.hidden||(t=0)};document.addEventListener("visibilitychange",r);let s=(a,c)=>{var l;if(t){let u=i.decodeFPS,h=u>0&&u<=5?600+1e3/u:600,m=c.presentationTime-t;if(m>h){m=Math.min(m,5e3);let _=`${i.userId}_${i.streamType}`,g=this._monitorFreezeData.get(_,"render");g?g.duration+=m:this._monitorFreezeData.set(_,{userId:i.userId,type:i.streamType,duration:m},"render");let E=this._renderFreezeMap.get(_);E?(E.totalDuration+=m,E.count+=1):this._renderFreezeMap.set(_,{userId:i.userId,type:i.streamType,totalDuration:m,count:1})}}t=c.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${i.userId}_${i.streamType}`,{onVisibilityChange:r})}onRemoteVideoPlayEnd({track:i,player:e}){let t=`${i.userId}_${i.streamType}`,r=this.eventListenerMap.get(t);r&&document.removeEventListener("visibilitychange",r.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},I_=nm;var R_=Je(at(),1);var Od=class{constructor(i,e,t,r,s,n=4/3){this.vbMode=i;this.faceDetectorHash=t;this.visionTaskRegistry=r;this.logger=s;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(i,e,t){let s=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];s&&(e?v.addSuccessEvent({key:s.key}):v.addFailedEvent({key:s.key,error:s.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20,this.boundaryY=r*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=s.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,u=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,u):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,u)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let s,n;return i>e/2?(s=e-t-r,n=t-s):(s=t,n=0),{min:s,offset:n}}calculateTargetPosition(i,e,t,r,s,n,a=.4){let c=i+t/2,l=e+r/2,u,h,{min:m,offset:_}=this.calculateBoundary(c,s,i,t),{min:g,offset:E}=this.calculateBoundary(l,n,e,r);return u=2*m+t,h=2*g+r,u/h>this.originalAspect?(u=h*this.originalAspect,_=c-u/2):(h=u/this.originalAspect,E=l-h/2),t/s>a&&(_=0,E=0,u=s,h=n),_=Math.max(0,Math.min(_,s-u)),E=Math.max(0,Math.min(E,n-h)),{sx:_,sy:E,cropWidth:u,cropHeight:h,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),s=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=M({},i),this.animationState.target=M({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let s=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),Q(this.animationState.current.scaleOffsetX)&&Q(this.animationState.target.scaleOffsetX)&&Q(this.animationState.current.scaleOffsetY)&&Q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(hr(i.sx-e.sx,2)+hr(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,s,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,s,n,i,e);this.processFacePositionCrop(c,i,e),s*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,s,n){var c,l,u,h,m,_,g,E,C,k,ae,w;let a={sx:t+s/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(h=(u=this.animationState.current)==null?void 0:u.scaleOffsetX)!=null?h:0,scaleOffsetY:(_=(m=this.animationState.current)==null?void 0:m.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(E=(g=this.animationState.target)==null?void 0:g.scaleRatio)!=null?E:1,scaleOffsetX:(k=(C=this.animationState.target)==null?void 0:C.scaleOffsetX)!=null?k:0,scaleOffsetY:(w=(ae=this.animationState.target)==null?void 0:ae.scaleOffsetY)!=null?w:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var pI=`#version 300 es
76
+ `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return p(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return p(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return p(this,null,function*(){try{let e=yield this._peerConnection.createOffer(g_);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Y.PUBLISH,responseCommand:G.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Pt||this.localAuxVideoTrack instanceof Pt,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:s,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,s)})}setSDPDirection(e,t,r="all"){let s=De(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),Jt(s)}acceptAnswer(e){return p(this,null,function*(){var t,r,s,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),h=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let _=this._isPublishingAux?f.AUXILIARY:f.BIG;c=yield this.setBandwidth({bandwidth:m,type:f.VIDEO,sdp:c,videoType:_})}h&&(c=yield this.setBandwidth({bandwidth:h,type:f.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:f.VIDEO,videoType:f.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this.setAnswer(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.send(Y.UPDATE_MUTE_STAT,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Pe(Ds.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,responseCommand:G.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Zt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{De(e).media.forEach((r,s)=>{if(r.type===f.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Mo&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(s){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=f.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===f.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===f.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===f.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===f.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(Je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}};M([Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ds.prototype,"publish",1),M([Rt(521715,!1)],Ds.prototype,"unpublish",1),M([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ds.prototype,"connect",1);var im=Ds,ia=im;var ra=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"_decodeMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,m,h,_,g,E,A,k,re;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===f.VIDEO){if(a.ssrc===r.video?(c=f.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=f.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=f.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!T(a.encoderImplementation)&&(c===f.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===f.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let Qe=2,N=this._prevEncoderImplementation;c===f.AUXILIARY&&(Qe=7,N=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:Qe,prevImplementation:N,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===f.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===f.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(u=i.localMainVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),S.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 if(a.type==="candidate-pair")Cr(a)&&(this.totalBytesSent=a.bytesSent,z(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)));else if(a.type==="media-source"){if(a.kind===f.AUDIO)e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,T((g=(_=(h=i.localMainAudioTrack)==null?void 0:h.sourceTrack)==null?void 0:_.stats)==null?void 0:g.deliveredFramesDuration)?a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration):e.audio.totalSamplesDuration=i.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(a.kind===f.VIDEO)if(a.trackIdentifier===i.getVideoTrackId(f.VIDEO))if((k=(A=(E=i.localMainVideoTrack)==null?void 0:E.sourceTrack)==null?void 0:A.stats)!=null&&k.deliveredFrames){let{deliveredFrames:P}=i.localMainVideoTrack.sourceTrack.stats;e.video.framesCaptured=P,i.localMainVideoTrack.stat.framesCaptured&&i.localMainVideoTrack.stat.framesCaptured>0&&P>=i.localMainVideoTrack.stat.framesCaptured?e.video.fpsCapture=Math.floor((P-i.localMainVideoTrack.stat.framesCaptured)/this.statInterval):e.video.fpsCapture=a.framesPerSecond}else e.video.fpsCapture=a.framesPerSecond;else a.trackIdentifier===i.getVideoTrackId(f.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond}if(!T(a.audioLevel)&&((re=i.localMainAudioTrack)!=null&&re.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let P=f.SMALL;a.trackIdentifier===i.getVideoTrackId(f.VIDEO)||a.ssrc===r.video?P=f.VIDEO:(a.trackIdentifier===i.getVideoTrackId(f.AUXILIARY)||a.ssrc===r.auxiliary)&&(P=f.AUXILIARY),e[P].frameWidth=a.frameWidth,e[P].frameHeight=a.frameHeight,e[P].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel(),c=i.localMainAudioTrack.getInternalAudioLevelAfter3A();e.audio.audioCaptureEnergyAfter3a=c,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===f.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===f.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===f.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=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getReceiverStats(i){return p(this,null,function*(){var r,s,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{var _,g;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let E=(h.mediaType||h.kind)===f.AUDIO;if(E){if(h.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=h.packetsReceived,e.audio.bytesReceived=h.bytesReceived,e.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(e.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(e.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(e.audio.concealedSamples=h.concealedSamples),h.silentConcealedSamples&&(e.audio.silentConcealedSamples=h.silentConcealedSamples);let{remoteAudioTrack:A}=i;A.stat.packetsReceived=h.packetsReceived,A.stat.bytesReceived=h.bytesReceived,A.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=A.stat.end2EndDelay,e.hasAudio=!0}else{if(K&&h.bytesReceived===0)return;let A;h.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=h.packetsReceived,e.video.bytesReceived=h.bytesReceived,e.video.packetsLost=h.packetsLost,e.video.framesReceived=h.framesReceived,e.video.framesDecoded=h.framesDecoded,e.video.fpsDecoded=h.framesPerSecond,e.hasVideo=!0,i.videoCodec=Bt[(_=this._decodeMap.get(h.codecId))==null?void 0:_.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,A=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==h.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${h.decoderImplementation}(${i.videoCodec}) HWDecoder: ${h.powerEfficientDecoder}`),S.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:h.decoderImplementation,codec:i.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,h.decoderImplementation))),h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=h.packetsReceived,e.auxiliary.bytesReceived=h.bytesReceived,e.auxiliary.packetsLost=h.packetsLost,e.auxiliary.framesReceived=h.framesReceived,e.auxiliary.framesDecoded=h.framesDecoded,e.auxiliary.fpsDecoded=h.framesPerSecond,A=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=A.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((g=this._decodeMap.get(h.codecId))==null?void 0:g.mimeType.split("/")[1].toLowerCase())||"h264"),A&&(A.stat.packetsReceived=h.packetsReceived,A.stat.bytesReceived=h.bytesReceived,A.stat.packetsLost=h.packetsLost,A.stat.framesReceived=h.framesReceived,A.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(A.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=A.stat.end2EndDelay)}h.jitterBufferDelay&&(E?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount,e.audio.estimatedPlayoutTimestamp=h.estimatedPlayoutTimestamp):h.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount,e.video.estimatedPlayoutTimestamp=h.estimatedPlayoutTimestamp):h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&Cr(h)&&(this.totalBytesReceived=h.bytesReceived,z(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));T(h.frameWidth)||((h.trackIdentifier===i.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(e.video.frameWidth=h.frameWidth,e.video.frameHeight=h.frameHeight,i.remoteVideoTrack.stat.frameWidth=h.frameWidth,i.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===i.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=h.frameWidth,e.auxiliary.frameHeight=h.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!T(h.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&h.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=h.audioLevel||0,e.audio.totalAudioEnergy=h.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((s=i.remoteAuxiliaryTrack.player.stat)==null?void 0:s.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps);let m=(e.audio.estimatedPlayoutTimestamp||0)-(e.video.estimatedPlayoutTimestamp||0);Math.abs(m)>150&&this._log.warn("av sync delay",m)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return p(this,null,function*(){let t={},r,s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let a=U(),c=yield n.getStats(),l=U();l-a>2e3&&this._log.warn(`getStats cost ${l-a}ms`);let u=[],m=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);c.forEach(h=>m.has(h.type)&&u.push(h)),this._spcStats=u}i&&(t=yield this.getSenderStats(i));for(let[n,a]of e){let c=yield this.getReceiverStats(a);s.push(c)}return e.size&&(r=this.getMediaPlayoutStats(this._spcStats)),{senderStats:t,receiverStats:s,mediaPlayoutStats:r}})}getDifferenceValue(i,e){if(fi(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t,uplinkConnection:r}){var h,_,g,E,A,k,re,P,Qe;if(!fi(i.senderStats)){let N={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&&(N.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Dt),T(i.senderStats.audio.audioCaptureEnergyAfter3a)||(N.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let b=[];if(i.senderStats.video.bytesSent){let ve={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};b.push(ve)}if(i.senderStats.small.bytesSent){let ve={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};b.push(ve)}if(i.senderStats.auxiliary.bytesSent){let ve={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};b.push(ve)}let te={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:N,msg_video_status:b,msg_network_status:te}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(N=>{let b={msg_user_info:{str_identifier:N.userId,uint64_tinyid:N.tinyId},msg_network_status:{uint32_rtt:N.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(N.hasAudio){let te={uint32_audio_p2p_delay:N.audio.p2pDelay,uint32_audio_cache_ms:N.audio.totalJitter,uint32_audio_cache_ms_count:N.audio.totalJitterCount,uint32_audio_codec_bitrate:N.audio.bytesReceived,uint32_audio_total_bitrate:N.audio.bytesReceived,uint32_audio_level:N.audio.audioLevel*1e8,uint32_audio_energy:N.audio.totalAudioEnergy*1e6,uint32_audio_receive:N.audio.packetsReceived,uint32_audio_origin_lost:N.audio.packetsLost};b.msg_audio_status=te}if(N.hasVideo){let te=t.get(`${N.userId}_${Zd}`),ve=te?te.duration:0,fe={uint32_video_stream_type:N.isSmallSubscribed?3:2,uint32_video_receive_fps:N.video.framesReceived,uint32_video_width:N.video.frameWidth,uint32_video_height:N.video.frameHeight,uint32_video_codec_bitrate:N.video.bytesReceived,uint32_video_receive:N.video.packetsReceived,uint32_video_origin_lost:N.video.packetsLost,uint32_video_block_time:ve,uint32_video_dec_fps:N.video.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.video.totalJitter,uint32_video_cache_ms_count:N.video.totalJitterCount,uint32_video_p2p_delay:N.video.p2pDelay,uint32_video_codec:N.video.codec};b.msg_video_status.push(fe)}if(N.hasAuxiliary){let te=t.get(`${N.userId}_${Kd}`),ve=te?te.duration:0,fe={uint32_video_stream_type:7,uint32_video_receive_fps:N.auxiliary.framesReceived,uint32_video_width:N.auxiliary.frameWidth,uint32_video_height:N.auxiliary.frameHeight,uint32_video_codec_bitrate:N.auxiliary.bytesReceived,uint32_video_receive:N.auxiliary.packetsReceived+N.auxiliary.packetsLost,uint32_video_origin_lost:N.auxiliary.packetsLost,uint32_video_block_time:ve,uint32_video_dec_fps:N.auxiliary.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.auxiliary.totalJitter,uint32_video_cache_ms_count:N.auxiliary.totalJitterCount,uint32_video_p2p_delay:N.auxiliary.p2pDelay,uint32_video_codec:N.video.codec};b.msg_video_status.push(fe)}e.msg_down_stream_info.push(b)}),i.mediaPlayoutStats&&!fi(i.mediaPlayoutStats)&&(i.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,i.mediaPlayoutStats.totalSamplesDuration*=1e3);let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let N=n.msg_up_stream_info.msg_audio_status,b=e.msg_up_stream_info.msg_audio_status;if(N.uint32_audio_codec_bitrate===0)b.uint32_audio_codec_bitrate=0;else{let te=this.getDifferenceValue(N.uint32_audio_codec_bitrate,b.uint32_audio_codec_bitrate);b.uint32_audio_codec_bitrate=Math.round(te*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=b.uint32_audio_codec_bitrate}(h=n.msg_device_info)!=null&&h.uint32_audio_capture_cost?(e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s),e.msg_device_info.uint32_audio_capture_cost>0&&((g=r==null?void 0:r.localMainAudioTrack)==null||g.updateAfter3aSilenceStartTime((_=i.senderStats.audio.audioCaptureEnergyAfter3a)!=null?_:i.senderStats.audio.micAudioLevel))):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(N=>{let b=c.find(xi=>xi.uint32_video_stream_type===N.uint32_video_stream_type);if(!b||b.uint32_video_codec_bitrate===0){N.uint32_video_codec_bitrate=0,N.uint32_video_enc_fps=0,N.uint32_video_codec_fps=0;return}let te=0,ve=0,fe=0;b&&N.uint32_video_codec_bitrate>=b.uint32_video_codec_bitrate&&(te=b.uint32_video_codec_bitrate,ve=b.uint32_video_enc_fps,fe=b.uint32_video_codec_fps);let Ye=this.getDifferenceValue(te,N.uint32_video_codec_bitrate);N.uint32_video_codec_bitrate=Math.round(Ye*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=N.uint32_video_codec_bitrate,N.uint32_video_enc_fps=Math.round(this.getDifferenceValue(ve,N.uint32_video_enc_fps)/s),N.uint32_video_codec_fps=Math.round(this.getDifferenceValue(fe,N.uint32_video_codec_fps)/s),b.uint32_video_width===0&&b.uint32_video_height===0&&b.uint32_video_codec_fps===0&&(N.uint32_video_codec_fps=N.uint32_video_enc_fps),T(b.uint32_key_frame_count)||(N.uint32_key_frame_count=Math.round(this.getDifferenceValue(b.uint32_key_frame_count,N.uint32_key_frame_count))),T(b.uint32_nack_count)||(N.uint32_nack_count=Math.round(this.getDifferenceValue(b.uint32_nack_count,N.uint32_nack_count))),T(b.uint32_pli_count)||(N.uint32_pli_count=Math.round(this.getDifferenceValue(b.uint32_pli_count,N.uint32_pli_count))),T(b.uint32_video_arq_packets)||(N.uint32_video_arq_packets=Math.round(this.getDifferenceValue(b.uint32_video_arq_packets,N.uint32_video_arq_packets))),T(b.uint32_encode_cost)||(N.uint32_encode_cost=Math.round(this.getDifferenceValue(b.uint32_encode_cost,N.uint32_encode_cost)/s)),T(b.uint32_send_packet_cost)||(N.uint32_send_packet_cost=Math.round(this.getDifferenceValue(b.uint32_send_packet_cost,N.uint32_send_packet_cost)/s))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(N=>u.find(b=>b.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid));let m=e.msg_down_stream_info;if(m.forEach(N=>{let b=u.find(te=>te.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid);if(!fi(N.msg_audio_status)&&!fi(b.msg_audio_status)){let te=N.msg_audio_status,ve=b.msg_audio_status,fe=this.getDifferenceValue(ve.uint32_audio_cache_ms_count,te.uint32_audio_cache_ms_count);delete te.uint32_audio_cache_ms_count,te.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(ve.uint32_audio_cache_ms,te.uint32_audio_cache_ms)/fe)||0;let Ye=this.room.remotePublishedUserMap.get(N.msg_user_info.str_identifier);Ye&&(Ye.remoteAudioTrack.stat.jitterBufferDelay=te.uint32_audio_cache_ms),te.uint32_audio_origin_lost=this.getDifferenceValue(ve.uint32_audio_origin_lost,te.uint32_audio_origin_lost),te.uint32_audio_receive=this.getDifferenceValue(ve.uint32_audio_receive,te.uint32_audio_receive),te.uint32_audio_receive+=te.uint32_audio_origin_lost;let xi=this.getDifferenceValue(ve.uint32_audio_codec_bitrate,te.uint32_audio_codec_bitrate);te.uint32_audio_codec_bitrate=Math.round(xi*8/s),te.uint32_audio_total_bitrate=Math.round(xi*8/s)}else N.msg_audio_status={};if(N.msg_video_status&&b.msg_video_status){let te=b.msg_video_status;N.msg_video_status=N.msg_video_status.filter(fe=>te.find(Ye=>Ye.uint32_video_stream_type===fe.uint32_video_stream_type)),N.msg_video_status.forEach(fe=>{let Ye=te.find(Y_=>Y_.uint32_video_stream_type===fe.uint32_video_stream_type),xi=Ye.uint32_video_receive,Bd=Ye.uint32_video_origin_lost,J_=Ye.uint32_video_codec_bitrate,j_=Ye.uint32_video_receive_fps,X_=Ye.uint32_video_dec_fps;fe.uint32_video_origin_lost=this.getDifferenceValue(Bd,fe.uint32_video_origin_lost),fe.uint32_video_receive=this.getDifferenceValue(xi,fe.uint32_video_receive)+fe.uint32_video_origin_lost;let z_=this.getDifferenceValue(J_,fe.uint32_video_codec_bitrate);fe.uint32_video_codec_bitrate=Math.round(z_*8/s);let Q_=this.getDifferenceValue(j_,fe.uint32_video_receive_fps);fe.uint32_video_receive_fps=Math.round(Q_/s),fe.uint32_video_dec_fps=Math.round(this.getDifferenceValue(X_,fe.uint32_video_dec_fps)/s);let B=this.getDifferenceValue(Ye.uint32_video_cache_ms_count,fe.uint32_video_cache_ms_count);delete fe.uint32_video_cache_ms_count,fe.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ye.uint32_video_cache_ms,fe.uint32_video_cache_ms)/B)||0})}}),!T((E=a==null?void 0:a.mediaPlayoutStats)==null?void 0:E.totalSamplesDuration)&&!T((A=i.mediaPlayoutStats)==null?void 0:A.totalSamplesDuration)){let N=2*Math.floor(this.getDifferenceValue((k=a==null?void 0:a.mediaPlayoutStats)==null?void 0:k.synthesizedSamplesDuration,(re=i.mediaPlayoutStats)==null?void 0:re.synthesizedSamplesDuration)/s),b=2*Math.floor(this.getDifferenceValue((P=a==null?void 0:a.mediaPlayoutStats)==null?void 0:P.totalSamplesDuration,(Qe=i.mediaPlayoutStats)==null?void 0:Qe.totalSamplesDuration)/s);e.msg_device_info.uint32_audio_play_cost=b-N}return a&&i.receiverStats.forEach(N=>{if(N.audio.concealedSamples&&N.audio.totalSamplesReceived){let b=a.receiverStats.find(te=>te.userId===N.userId);if(b&&b.audio.concealedSamples&&b.audio.totalSamplesReceived){let te=(N.audio.silentConcealedSamples||0)-(b.audio.silentConcealedSamples||0),ve=N.audio.concealedSamples-b.audio.concealedSamples,fe=N.audio.totalSamplesReceived-b.audio.totalSamplesReceived,Ye=Math.floor((ve-te)/fe*1e3*s);if(Ye>s*1e3/5){let xi=m.find(Bd=>Bd.msg_user_info.str_identifier===N.userId);xi&&(xi.msg_audio_status.uint32_audio_block_time=Ye)}}}}),e.msg_down_stream_info.forEach(N=>{N.msg_video_status.forEach(b=>{b.uint32_video_codec_bitrate===0&&b.uint32_video_receive_fps===0&&(b.uint32_video_width=0,b.uint32_video_height=0)})}),e}getStatsReport(r){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let s={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,uint32_audio_capture_energy_after3a: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(s))),this.prepareReport({stats:n,report:s,freezeMap:t,uplinkConnection:i}),this._prevReportTime=Date.now(),s})}getMediaPlayoutStats(i){let e;if(Ie(i)){for(let t of i)if(t.type==="media-playout"){let{synthesizedSamplesDuration:r,totalSamplesDuration:s}=t;e={synthesizedSamplesDuration:r,totalSamplesDuration:s};break}return e}}reset(){var i;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,(i=this.room.localMainVideoTrack)!=null&&i.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}};var S_=Ge(at());function T_(o){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===o){let r=Math.round(t.duration),s=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),m=Math.round(t.responseStart-t.requestStart),h=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(O({},i),{totalCost:r,local:s,redirect:n,httpCache:a,dns:c,tcp:u,tls:l,request:m,response:h});break}}catch(e){}return i}function E_(o){return new Promise(i=>p(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${o}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let s=T_(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var hI=700,Ro=class Ro extends S_.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=R.createLogger({parent:t.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(G.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Se.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let s=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=s-n;s===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/s*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===Ce.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:m});continue}let h=0,_=this._downlinkPrevStatMap.get(c),g=u-_.totalPacketsLost,E=m-_.totalPacketsReceived;g<=0||E<0?h=0:h=Math.round(g/(g+E)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:h,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:s,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,s)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!oo())return t;let r=e.getReceivers();try{for(let s=0;s<r.length;s++)(yield r[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&z(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===f.AUDIO||c.mediaType===f.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(s){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===Ce.DISCONNECTED||e.connectionState===Ce.FAILED||e.connectionState===Ce.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=oe.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];S.emit(C.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(O({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Ro.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-Ro.lastPingTime>t.interval*1e3){Ro.lastPingTime=Date.now();let a=t.domain.map(c=>E_(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>hI),this.pingResults.timestamp=s,this.pingResults.data=c,c.forEach(l=>{v.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(oe.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:s,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:n})}})}};d(Ro,"EVENT_NETWORK_QUALITY","0"),d(Ro,"lastPingTime",0);var Ms=Ro;function mI({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return Tr(t)?t.catch(r=>R.error(`${o.name}() error observed ${r}`)):t}catch(t){R.error(`${o.name}() error observed ${t}`)}}}var Dd=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=R.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&le(this[e])&&(this[e]=mI({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:He,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,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Yr().then(()=>{this._basicInfo.string_os_version=ni(),this._basicInfo.string_device_name=si()||this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),S.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(C.JOIN_START,this.handleJoinStart).addEvent(C.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(C.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(C.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(C.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(C.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(C.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(C.JOIN_FAILED,this.handleJoinFailed).addEvent(C.LEAVE_START,this.handleLeaveStart).addEvent(C.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(C.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(C.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(C.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(C.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(C.PUBLISH_START,this.handlePublishStart).addEvent(C.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(C.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(C.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(C.PLAY_TRACK_START,this.handlePlayStart).addEvent(C.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(C.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===f.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(C.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(C.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(C.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(C.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(C.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(C.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>S.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),oe.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&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:s,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.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){var e;if(this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0){if(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;let t=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;t&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=U()-t)}else 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())}handleSwitchRoomStart(i){if(this.hitTest(i.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:i}){if(this.hitTest(i)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let s={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:L(O({},pI),{msg_user_info:new oa({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,s)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:s,tinyId:n,role:a}=e,c=new oa({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${s}_${t}`,m=this._remoteStreamStatMap.get(u);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.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:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.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:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,s=this._remoteStreamStatMap.get(r);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,v.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,u,m;s&&(l=s,u=1),n&&(c=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:m,videoDelayCount:u})}}))}handleHeartbeatStats(i){var e;if(this.hitTest(i.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:s}=i.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:n}=r.msg_audio_status;Math.floor(n/Dt*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Dt,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:c,msg_video_status:l}=n,u=a.str_identifier,m=this._room.remotePublishedUserMap.get(u);if(l.forEach(h=>{let _=h.uint32_video_stream_type===2,g=h.uint32_video_stream_type===7,E=`${u}_${_?"main":"auxiliary"}`,A=this._remoteStreamStatMap.get(E);if(A&&(_&&(m!=null&&m.remoteVideoTrack.isSubscribed)||g&&(m!=null&&m.remoteAuxiliaryTrack))){A.totalVideoFPS+=h.uint32_video_receive_fps,A.totalVideoBitrate+=h.uint32_video_codec_bitrate,A.videoCount++,A.statsToReport.uint32_video_width===0&&(A.statsToReport.uint32_video_width=h.uint32_video_width),A.statsToReport.uint32_video_height===0&&(A.statsToReport.uint32_video_height=h.uint32_video_height);let k=_?m.remoteVideoTrack:m.remoteAuxiliaryTrack;k.stat.jitterBufferDelay&&(A.videoJitterBufferDelay=k.stat.jitterBufferDelay),k.stat.framesReceived&&(A.statsToReport.uint32_video_consume_render_rate=Math.floor(k.stat.framesDecoded/k.stat.framesReceived*hr(10,6)))}}),!Uo(c)){let h=`${u}_main`,_=this._remoteStreamStatMap.get(h);this._remoteStreamStatMap.has(h)&&_&&m!=null&&m.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,m.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=m.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/Dt*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/Dt,_.audioLevelCount++),c.uint32_audio_block_time&&(_.statsToReport.uint32_audio_block_time+=c.uint32_audio_block_time))}}),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.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)),t.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof D?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&fr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&_r)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Br)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:m,audioDelayCount:h,videoDelayCount:_,totalAudioDelay:g,totalVideoDelay:E}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/m),h&&g&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(g/h),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&E&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(E/_))}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:s}=this._room;s&&(i.statsToReport.uint32_audio_play_time=s.getDuration(e,f.AUDIO),i.statsToReport.uint32_video_play_time=s.getDuration(e,f.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,yo));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_audio_block_time=Math.min(i.statsToReport.uint32_audio_block_time,i.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>yo&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),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>yo&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>yo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+yo)}getReportData(){this._basicInfo.uint32_networkType=qr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new oa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Vo(this._signalInfo.relayIp),uint32_client_ip:Vo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*hr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Vo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Js(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return p(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=Ir.enable?Gi(i,2001,e):yield El(i),r=t instanceof ArrayBuffer,s=`${Wi(e,mr.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t));let a=[this.uploadKVStat(v),this.uploadKVStat(ro)];n||a.push(qi({url:s,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(O({},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=Ir.enable?Gi(e,2003,this._room.sdkAppId):yield El(e),r=t instanceof ArrayBuffer,s=`${Wi(+this._room.sdkAppId,mr.KV_STAT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||qi({url:s,body:t})})}};M([Mt({settings:{timeout:500,retries:3}})],Dd.prototype,"upload",1);var yo=5e3,pI={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},oa=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},I_=Dd;var rm=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=U())}stop(){this._endTime===0&&(this._endTime=U())}getDuration(){return this._endTime===0?U()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Md=rm;var om=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(C.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(C.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,f.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,f.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,f.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);s&&(!e.hasAudio&&t.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,f.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,f.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,f.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,s=new Md,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(r,{userId:i,type:t,audio:e===f.AUDIO?[s]:[],video:e===f.AUDIO?[]:[s]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(s=>s.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,s)=>r+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},A_=om;var sm=class{constructor(){d(this,"renderFreezeMap",new Map);d(this,"dataFreezeMap",new Map)}get(i,e){let t=this.renderFreezeMap.get(i),r=this.dataFreezeMap.get(i);return e?e==="data"?r:t:(Re||K)&&t&&r&&t.duration>r.duration?t:r}set(i,e,t){t==="data"?this.dataFreezeMap.set(i,e):this.renderFreezeMap.set(i,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},nm=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new sm);d(this,"_eventMap",new Map);d(this,"_videoEncodeFailedCount",0);d(this,"_audioEncodeFailedCount",0);d(this,"_encodeFailedThreshold",3);d(this,"eventListenerMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(C.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(C.PLAY_TRACK_START,this.onPlayTrackStart).set(C.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,s=`${r}_${e}`;this.stopDataFreeze({key:s,userId:r,type:e})}).set(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let s="main",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}if(e.hasAuxiliary&&!t.hasAuxiliary){let s="auxiliary",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}}).set(C.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==f.VIDEO)){if(e==="PLAYING"){let s=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}t===f.MUTE?this.onVideoTrackMuted(i):t===f.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(C.HEARTBEAT_REPORT,this.onHearBeatReport).set(C.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(C.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,s=this._dataFreezeMap.get(r),n=new Md;s?s.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){if(this.hitTest(i)){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0||r!=null&&r.isUseCustomSource)return;t.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(r!=null&&r.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&se.uploadEvent({userId:this._room.userId,log:`stat-${Ze.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&se.uploadEvent({userId:this._room.userId,log:`stat-${Ze.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let s=r.durationItemList[r.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Sa){let a=this._monitorFreezeData.get(i,"data");this._monitorFreezeData.set(i,{userId:e,type:t,duration:a?a.duration+n:n},"data")}else r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==f.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Sa&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e={renderFreeze:0,count:0},t=this._renderFreezeMap.get(i);return t&&(e.renderFreeze=t.totalDuration,e.count=t.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}onRemoteVideoPlayStart({track:i,player:e}){var n;if(!Ki())return;let t=0,r=()=>{document.hidden||(t=0)};document.addEventListener("visibilitychange",r);let s=(a,c)=>{var l;if(t){let u=i.decodeFPS,m=u>0&&u<=5?600+1e3/u:600,h=c.presentationTime-t;if(h>m){h=Math.min(h,5e3);let _=`${i.userId}_${i.streamType}`,g=this._monitorFreezeData.get(_,"render");g?g.duration+=h:this._monitorFreezeData.set(_,{userId:i.userId,type:i.streamType,duration:h},"render");let E=this._renderFreezeMap.get(_);E?(E.totalDuration+=h,E.count+=1):this._renderFreezeMap.set(_,{userId:i.userId,type:i.streamType,totalDuration:h,count:1})}}t=c.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${i.userId}_${i.streamType}`,{onVisibilityChange:r})}onRemoteVideoPlayEnd({track:i,player:e}){let t=`${i.userId}_${i.streamType}`,r=this.eventListenerMap.get(t);r&&document.removeEventListener("visibilitychange",r.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},C_=nm;var b_=Ge(at(),1);var Od=class{constructor(i,e,t,r,s,n=4/3){this.vbMode=i;this.faceDetectorHash=t;this.visionTaskRegistry=r;this.logger=s;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(i,e,t){let s=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];s&&(e?v.addSuccessEvent({key:s.key}):v.addFailedEvent({key:s.key,error:s.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20,this.boundaryY=r*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=s.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,u=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,u):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,u)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let s,n;return i>e/2?(s=e-t-r,n=t-s):(s=t,n=0),{min:s,offset:n}}calculateTargetPosition(i,e,t,r,s,n,a=.4){let c=i+t/2,l=e+r/2,u,m,{min:h,offset:_}=this.calculateBoundary(c,s,i,t),{min:g,offset:E}=this.calculateBoundary(l,n,e,r);return u=2*h+t,m=2*g+r,u/m>this.originalAspect?(u=m*this.originalAspect,_=c-u/2):(m=u/this.originalAspect,E=l-m/2),t/s>a&&(_=0,E=0,u=s,m=n),_=Math.max(0,Math.min(_,s-u)),E=Math.max(0,Math.min(E,n-m)),{sx:_,sy:E,cropWidth:u,cropHeight:m,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),s=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=O({},i),this.animationState.target=O({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let s=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),z(this.animationState.current.scaleOffsetX)&&z(this.animationState.target.scaleOffsetX)&&z(this.animationState.current.scaleOffsetY)&&z(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(hr(i.sx-e.sx,2)+hr(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,s,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,s,n,i,e);this.processFacePositionCrop(c,i,e),s*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,s,n){var c,l,u,m,h,_,g,E,A,k,re,P;let a={sx:t+s/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(m=(u=this.animationState.current)==null?void 0:u.scaleOffsetX)!=null?m:0,scaleOffsetY:(_=(h=this.animationState.current)==null?void 0:h.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(E=(g=this.animationState.target)==null?void 0:g.scaleRatio)!=null?E:1,scaleOffsetX:(k=(A=this.animationState.target)==null?void 0:A.scaleOffsetX)!=null?k:0,scaleOffsetY:(P=(re=this.animationState.target)==null?void 0:re.scaleOffsetY)!=null?P:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var fI=`#version 300 es
71
77
  in vec2 a_position;
72
78
  in vec2 a_texCoord;
73
79
  out vec2 v_texCoord;
74
80
  void main() {
75
81
  gl_Position = vec4(a_position.x, a_position.y, 0, 1);
76
82
  v_texCoord = a_texCoord;
77
- }`,fI=`#version 300 es
83
+ }`,_I=`#version 300 es
78
84
  precision highp float;
79
85
  uniform sampler2D u_texture;
80
86
  uniform sampler2D mask;
@@ -83,7 +89,7 @@ in vec2 v_texCoord;
83
89
  out vec4 outColor;
84
90
  void main() {
85
91
  outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
86
- }`,Md=class extends Gt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"predictReady");d(this,"_color");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_colorLocation");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"_mat4");d(this,"_postProcessing");d(this,"_onAbort");d(this,"_visionTaskRegistry");d(this,"resolvePreditReady");this.init(t).catch(r=>{e.log.error(r),e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`})),this.resolvePreditReady()})}init(e){return f(this,null,function*(){var n,a,c;this.predictReady=new Promise(l=>{this.resolvePreditReady=l});let t=e.Wasm,r=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this._enableEffectOptimization=(a=e.enableEffectOptimization)!=null?a:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:l,y:u,width:h,height:m}=e.waterMark;this.wasm.setWaterMark(l,u,h,m)}if(e.beautyParams){let{beauty:l,brightness:u,ruddy:h}=e.beautyParams;this.wasm.setBeauty(l,u,h,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=r.getUniformLocation(this.program,"u_color"),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let l=this.context.createShader(r.FRAGMENT_SHADER,fI),u=this.context.createShader(r.VERTEX_SHADER,pI);this._prePrograme=this.context.createProgram(u,l),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(this.wasm.vbMode===2||this.wasm.vbMode===3)?an()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(c=this._postProcessing)==null||c.init(r,this.positionBuffer,this.texCoordBuffer,4/3):this._postProcessing=void 0,yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new Od(this.wasm.vbMode,this.image,t,this._visionTaskRegistry,this.context.log)}catch(t){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let r=this.getMaskTexture(e);if(!r)return;let s=r;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,s=this._postProcessing.postProcessing(r)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,s||null),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.wasm.vbMode===3&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),bt(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(bt(this.wasm.rotation)&&!this._visionTaskRegistry&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}if(this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let c=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,c||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return 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)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:c}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/c,0]),this._mat4.scale(l,l,[r/a,s/c,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}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),this._postProcessing&&this._postProcessing.close(),(t=this.wasm)==null||t.close()}};var kd=class extends Ue{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
92
+ }`,kd=class extends Wt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"predictReady");d(this,"_color");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_colorLocation");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"_mat4");d(this,"_postProcessing");d(this,"_onAbort");d(this,"_visionTaskRegistry");d(this,"resolvePreditReady");this.init(t).catch(r=>{e.log.error(r),e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`})),this.resolvePreditReady()})}init(e){return p(this,null,function*(){var n,a,c;this.predictReady=new Promise(l=>{this.resolvePreditReady=l});let t=e.Wasm,r=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this._enableEffectOptimization=(a=e.enableEffectOptimization)!=null?a:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:l,y:u,width:m,height:h}=e.waterMark;this.wasm.setWaterMark(l,u,m,h)}if(e.beautyParams){let{beauty:l,brightness:u,ruddy:m}=e.beautyParams;this.wasm.setBeauty(l,u,m,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=r.getUniformLocation(this.program,"u_color"),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let l=this.context.createShader(r.FRAGMENT_SHADER,_I),u=this.context.createShader(r.VERTEX_SHADER,fI);this._prePrograme=this.context.createProgram(u,l),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(this.wasm.vbMode===2||this.wasm.vbMode===3)?an()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(c=this._postProcessing)==null||c.init(r,this.positionBuffer,this.texCoordBuffer,4/3):this._postProcessing=void 0,yield this.initVisionTasks(e)})}initVisionTasks(e){return p(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new Od(this.wasm.vbMode,this.image,t,this._visionTaskRegistry,this.context.log)}catch(t){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let r=this.getMaskTexture(e);if(!r)return;let s=r;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,s=this._postProcessing.postProcessing(r)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,s||null),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.wasm.vbMode===3&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),bt(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(bt(this.wasm.rotation)&&!this._visionTaskRegistry&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}if(this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let c=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,c||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return 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)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:c}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/c,0]),this._mat4.scale(l,l,[r/a,s/c,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}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),this._postProcessing&&this._postProcessing.close(),(t=this.wasm)==null||t.close()}};var Pd=class extends Ue{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
87
93
  precision highp float;
88
94
  uniform sampler2D ySampler;
89
95
  uniform sampler2D uSampler;
@@ -108,15 +114,9 @@ void main() {
108
114
  void main() {
109
115
  gl_Position = vertexPos;
110
116
  textureCoord = texturePos;
111
- }`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),s}render(e){let t=this.context.ctx,r=this.width,s=this.height;return this.useProgram(),t.viewport(0,0,r,s),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,s,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var A_=(o,i)=>{switch(o){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function _I(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var gI=0,Pd=class{constructor(i){d(this,"id",gI++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=ot(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=de(e.availableState,q.OFF),this.stopOB=ot(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),le(this.stateChangeOB,mh((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),ke(this.stopOB),Ee()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=le(this.pipe(this.track),ke(this.stopOB),rr());le(e,Ee(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),v.addFailedEvent({key:A_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),v.addFailedEvent({key:514704});else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),v.addSuccessEvent({key:A_(this.type,this.renderer)}),v.addSuccessEvent({key:514704})})),le(e,or(1),Ee(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!fn()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!_I(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,s=!1;switch(r){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=U();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(c=i.getMetadata)==null?void 0:c.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>f(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new Fe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Fe.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new kd(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new ze({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{c.image=u,c.update()}catch(h){delete this.goodType,i.log.error(h),e.error(11)}});let l=new fo(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var C_=Promise.resolve(),sa=class extends R_.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"_rotation",0);d(this,"cameraTrack");d(this,"cameraNode");d(this,"transformNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"onAbort");d(this,"_color");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"mixTrack");d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log");d(this,"_mat4");d(this,"_postProcessing");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"updated",C_);d(this,"_updateFlag",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new ze({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var r;let{width:e,height:t}=((r=this.cameraTrack)==null?void 0:r.settings)||{};return bt(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new ze({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Fe({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(Nl<=22),this._glVideoContext.on(Fe.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,t,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ft||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:r,error:t}):v.addSuccessEvent({key:r})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new Fe({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}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Zc(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Fe.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(r,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:s,player:n}=r;Ft&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return f(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),et===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Gt?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Gt?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new Yc(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ue.RENDER,l=>{var u;(u=this.cameraTrack)==null||u.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,c=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new Md(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Jt(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new gs(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;else if(this.waterMarkNode){let{width:c,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(c,l),c&&l&&this.waterMarkNode.resize(c,l)}(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"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.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)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,s,n,a;if(e instanceof Pt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Xe)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof ki){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let c=e.mediaTrack;return e.setOutputMediaStreamTrack(c)}if(e instanceof go)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var t;e instanceof Pt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Xe?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ki?e.source&&e.source.context.destroy():e instanceof go&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return f(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let s=r.getContext("2d");if(!s)throw new D({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:u,fillVideo:h})=>{let m=h&&e||l,_=h&&t||u,g=h?0:a,E=h?0:c;s.drawImage(n,g,E,m,_)}),Ho(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.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 Ho((e==null?void 0:e.imageElement)||e.imageUrl)}catch(m){throw new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:s=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2,fillVideo:u=!1}=e;this.watermarkImageList.some(m=>m.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(m=>m.type!==c),this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:u}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:u}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(m,_)=>m==="imageUrl"?void 0:_))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return f(this,null,function*(){var t,r,s;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 Ho(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(r=e.enableEffectOptimization)!=null?r:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}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 D({code:I.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._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Pd(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};O([kc(function(e){this.log.error("update failed",e)}),Y(e=>function(...t){return f(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield C_,this.updated=new Promise((r,s)=>{e.apply(this,t).then(r,s),setTimeout(s,5e3,new D({code:I.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],sa.prototype,"update",1);var TI=0;var wd=class extends q{constructor(e){super("room");d(this,"seq",++TI);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localPublishFlag",0);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"smallMode","canvas");d(this,"enableChorus",!1);d(this,"_isUsingCachedSchedule",!1);d(this,"_log");d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"heartbeatCount",0);d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this._log=R.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,me(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),me(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),me(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new E_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new S_({room:this}),this.badCaseDetector=new I_({room:this}),this.audioManager=new td(this),this.videoManager=new sa(this)}get videoCodec(){return"h264"}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 localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}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}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}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(ie(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(dt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(dd([a,a]),Br(`https://${a}`)):(s&&Br(s),n&&dd(n))}S.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:wi.main,sched_back_domain:wi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let s=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=s.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new D({code:I.INVALID_OPERATION,message:H({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(je.INVALID_DESTROY),new D({code:I.INVALID_OPERATION,message:H({key:B.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,S.emit(A.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var s,n,a,c;let r=U();try{let{isCached:l,result:u,detailCost:h}=yield bh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:$e,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${_t(u,{keysToExclude:["username","credential"]})}`),l&&S.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=M(M({},this.scheduleResult),u),Q((s=u.config)==null?void 0:s.retryCount)&&el(u.config.retryCount),ie((n=u.config)==null?void 0:n.loggerDomain)&&Br(u.config.loggerDomain),this.videoDecodeFallbackType=((a=u.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=u.config)==null?void 0:c.smallMode)||this.smallMode,S.emit(A.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),v.addSuccessEvent({key:521700,cost:U()-r})}catch(l){throw v.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var x_=Je(at());var am=Je(Zh());var y_=o=>{let i=Ne(o),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var s;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((s=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function b_(o){var e;let i=[];for(let t=0;t<o.rtp.length;t++){if(["rtx","red","ulpfec"].includes(o.rtp[t].codec))continue;let r=o.fmtp.filter(s=>s.payload===o.rtp[t].payload)[0];i.push({payload:o.rtp[t].payload,codec:o.rtp[t].codec,fmtp:r?r.config:"",rate:o.rtp[t].rate,rtx:((e=o.rtp[t+1])==null?void 0:e.codec)==="rtx"?o.rtp[t+1].payload:0,rtcpfb:((o==null?void 0:o.rtcpFb)||[]).filter(s=>s.payload===o.rtp[t].payload).map(({type:s,subtype:n})=>({id:s,params:n?[n]:[]}))})}return i}function EI(){return f(this,null,function*(){let o=new RTCPeerConnection;o.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield o.createOffer();if(!i.sdp)return[];let e=Ne(i.sdp),t=b_(e.media[0]);return o.close(),t})}var v_=(o,i)=>f(void 0,null,function*(){var a;let e=Ne(o),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],s=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(c=>({id:c.value,uri:c.uri}))),s.ext&&(t.video.extensions=s.ext.map(c=>({id:c.value,uri:c.uri})));for(let c of r.rtp){if(c.codec!=="opus")continue;let l=r.fmtp.find(h=>h.payload===c.payload);if(!l)continue;let u={codec:c.codec,fmtp:l.config,payload:l.payload,rate:c.rate,channels:c.encoding,rtcpfb:[],rtx:0};(a=r.rtcpFb)==null||a.forEach(({payload:h,type:m,subtype:_})=>{if(h===u.payload){let g={id:m,params:[]};_&&g.params.push(_),u.rtcpfb.push(g)}}),t.audio.codecs.push(u);break}let n=["h264","vp8","h265"];return i&&n.shift(),t.video.codecs=[...b_(s)].filter(c=>n.includes(c.codec.toLocaleLowerCase())),t.video.decoders=(yield EI()).filter(c=>["h264","vp8","h265"].includes(c.codec.toLocaleLowerCase())),t}),N_=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Ne(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:o.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[{payload:o.audio.codecs[0].payload,config:o.audio.codecs[0].fmtp}],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:"0",payloads:String(o.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:p.AUDIO,setup:o.dtls.setup,rtcpFb:o.audio.codecs[0].rtcpfb.map(a=>({payload:o.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:o.audio.codecs[0].payload,codec:o.audio.codecs[0].codec,rate:o.audio.codecs[0].rate,encoding:o.audio.codecs[0].channels}]};return s.media.push(n),[1,2,3].forEach(a=>{s.media.push(cm({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),jt(s)},cm=({mid:o,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let s={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(o),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:p.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Vr(s,a)})}else{let n;i.useH265?n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()==="h265"):n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let a=i.video.codecs[n]||e.video.codecs[0];Vr(s,a)}return s},Vr=(o,i)=>{o.payloads=`${o.payloads} ${i.payload}`.trim(),o.fmtp.push({payload:i.payload,config:i.fmtp}),o.rtcpFb=[...o.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],o.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(o.payloads=`${o.payloads} ${i.rtx}`,o.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),o.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function SI(o){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"]);o.ext&&(o.ext=o.ext.filter(e=>!i.has(e.uri)))}function II(o){if(!o.rtcpFb)return;let i=[];o.rtcpFb.forEach((e,t)=>{var r;i.push(e),o.rtcpFb&&((r=o.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),o.rtcpFb=i}function AI(o){o.type===p.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function CI(o){o.type===p.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var D_=(o,i,e)=>{let t=am.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===p.AUDIO||r.type===p.VIDEO)&&(II(r),AI(r),CI(r),SI(r),r.type===p.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Vr(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>Vr(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),am.default.write(t)};var O_=Je(at());var Ld=class extends O_.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!_e&&We&&S.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:s}){if(!(e||t===7||s!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth} fps health: ${this.mainFpsHealth}`),this.emit("1",{isAux:!1}))))}destroy(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(Ld,"EVENT_BAD_HEALTH","bad_health");var M_=Ld;function k_({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e()})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function P_({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)):videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:o,streamType:i})})}})}),r.enqueue(s)}})}function w_(o){let i=[sr],e=[Vh,xh,Uh,Lh,k_,P_,Pa,ka],t=()=>{let l=[],u=[],h=[],m=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(l.push(_.data.data),_.data.small&&h.push(_.data.data)):u.push(_.data.data);break;case"ntp-offset":m=_.data.data;break}},self.onrtctransform=_=>{let{options:g}=_.transformer,E=g.isReceiver?P_({userId:g.userId,streamType:g.streamType,isAudio:g.isAudio}):k_({getNtpTime:()=>Date.now()+m,isAudio:g.isAudio,isMain:g.isMain,seiMessageList:g.isMain?g.small?h:l:u});_.transformer.readable.pipeThrough(E).pipeTo(_.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
112
- const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
113
- const audioEncodePipeline = [${o.audioEncodePipeline.toString()}];
114
- const audioDecodePipeline = [${o.audioDecodePipeline.toString()}];`,s=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
115
- `)}
116
- ${e.map(l=>l.toString()).join(`
117
- `)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var xi=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(xi||{}),U_=0,V_=!1,RI=new Set,yI=o=>U_>2&&!V_&&RI.size===0&&o,bI=1,Xt=class extends x_.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"isDestroyed",!1);d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearWaitForConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);d(this,"originOffer",null);d(this,"autoSubscribedSsrcGroups",new Map);d(this,"autoSubscribedUserMap",new Map);d(this,"_h265DecodeFailed",!1);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=R.createLogger({parent:this._room.getLogger(),id:`spc${bI++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(mi?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destroy"),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 isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var t,r,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useH265?"h265":(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,r;return(e=this._serverAbility)!=null&&e.useH265&&((t=this._serverAbility)!=null&&t.video.decoders.find(s=>s.codec.toLowerCase()==="h265"))&&!this._h265DecodeFailed?"h265":(r=this._serverAbility)!=null&&r.video.decoders.find(s=>s.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?y_(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){}initScriptTransformWorker(){ns&&(this.scriptTransformWorker=w_({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"?this.emit("sei-message",e.data):e.data.type,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var s;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(s=this._peerConnection)==null?void 0:s.getConfiguration().encodedInsertableStreams;return wa(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return f(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let 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._signalChannel.clearBakRelayIps(),v.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&v.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let s=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[s==="closed"?"debug":"info"](`signaling state: ${s}`)},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 n=new lm(s.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield v_(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,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}
118
- offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return f(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e,(r,s)=>r==="username"||r==="credential"?"hided":s)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let s=r.getParameters();s.encodings[0]&&(s.encodings[0].priority=e,s.encodings[0].networkPriority=e,r.setParameters(s).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,s,n,a;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let c=U();if(((s=this._room.joinParams)==null?void 0:s.videoProfileLevel)==="high"){let h=this.clientAbility.video.codecs.find(m=>m.fmtp.includes("profile-level-id=64"));if(h){let m=e.video.codecs.findIndex(_=>_.codec.toLowerCase()===h.codec.toLowerCase());e.video.codecs[m]=h,this._log.warn("set new profile level id",h)}}let l={type:"answer",sdp:N_({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(l),yield this.waitForPeerConnectionConnected();let u=((n=this._room.scheduleResult.config)==null?void 0:n.priority)||((a=this._room.joinParams)==null?void 0:a.priority)||new URLSearchParams(location.search).get("priority");u&&this.setPriority(u),t||v.addSuccessEvent({key:521703,cost:U()-c})}catch(c){let l=c instanceof D&&c.code===I.API_CALL_ABORTED;throw l||this._log.error(`connect failed: ${c}`,e),this.reset(),!l&&!this.isReconnecting&&!this.isDestroyed&&(v.addFailedEvent({key:521703,error:c}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),c}})}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(Ie.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=M({ability:t},e),s=yield this._signalChannel.sendWaitForResponse({command:Z.REBUILD_PEER_CONNECTION,responseCommand:G.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new D({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(A.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting||this.isDestroyed)return;if(e!=null&&e.message.includes("timeout")){let t=Kt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ke(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),v.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Hi()&&this._log.warn(`SDK has tried reconnect for ${Hi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Re.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var s;let t=((s=this._peerConnection)==null?void 0:s.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===Re.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Re.FAILED||e.target.connectionState===Re.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Re.CONNECTED||e.target.connectionState===Re.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(A.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Yt;let e=null;return!Rr()||this._peerConnection.getSenders().length===0?Yt:(e=this._peerConnection.getSenders()[0].transport,!oo()||this._peerConnection.getReceivers().length===0?Yt:e?e.state:Yt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(xi.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Cr(r)){let s=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);s&&(this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.relayProtocol?`relayProtocol:${s.relayProtocol} url: ${s.url}`:""}`),s.networkType&&va(s.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(A.LEAVE_SUCCESS,s,this),this.off(xi.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});U_+=1,yI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),V_=!0,this.emit(xi.FIREWALL_RESTRICTION)),t(c)},Fs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(A.LEAVE_SUCCESS,s,this),this.on(xi.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let s=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=p.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var _;return(_=m.ssrcs)==null?void 0:_.find(g=>{var E;return(E=g.value)==null?void 0:E.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(s.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[0])),c=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[1])),l=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[2]));else if(s.length===0){this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=cm({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ne(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(m)),l=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${p.MAIN} ${u}-audio`}],c.direction=p.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:h},{id:e.auxiliary,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive",s.ssrcs=[],s.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(s=>this._downlinkMIDUserIDMap.delete(s)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:s,auxVideo:n}=e;try{if(Tn()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],h;l===0&&t?h=t:l===1&&r?h=r:l===2&&s?h=s:l===3&&n&&(h=n),h&&(yield this.setSenderMaxBitrate(u,h))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,s;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp)),(s=this._parsedAnswer.media[e])!=null&&s.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();if((!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited")delete r.encodings[0].maxBitrate;else{if(r.encodings[0].maxBitrate===t*1e3)return;r.encodings[0].maxBitrate=t*1e3}return e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=Ne(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp));let a=te?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}]);let c={type:"offer",sdp:jt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let s=e.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);let n=s.encodings[0].scaleResolutionDownBy;if(T(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}setDegradationPreference(e,t,r){if(We&&qe<83||Te&&nn(Tt,"12.1")||te&&qo<138)return;let s=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),s.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),s.degradationPreference=n,e.setParameters(s).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=jt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,s)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(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)}
117
+ }`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),s}render(e){let t=this.context.ctx,r=this.width,s=this.height;return this.useProgram(),t.viewport(0,0,r,s),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,s,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var R_=(o,i)=>{switch(o){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function gI(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var TI=0,wd=class{constructor(i){d(this,"id",TI++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=ot(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=ce(e.availableState,J.OFF),this.stopOB=ot(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),de(this.stateChangeOB,mh((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),ke(this.stopOB),Te()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=de(this.pipe(this.track),ke(this.stopOB),rr());de(e,Te(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),v.addFailedEvent({key:R_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),v.addFailedEvent({key:514704});else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),v.addSuccessEvent({key:R_(this.type,this.renderer)}),v.addSuccessEvent({key:514704})})),de(e,or(1),Te(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!fn()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!gI(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,s=!1;switch(r){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=U();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(c=i.getMetadata)==null?void 0:c.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>p(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new Be({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Be.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new Pd(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new Xe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{c.image=u,c.update()}catch(m){delete this.goodType,i.log.error(m),e.error(11)}});let l=new fo(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var y_=Promise.resolve(),sa=class extends b_.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"_rotation",0);d(this,"cameraTrack");d(this,"cameraNode");d(this,"transformNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"onAbort");d(this,"_color");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"mixTrack");d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log");d(this,"_mat4");d(this,"_postProcessing");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"updated",y_);d(this,"_updateFlag",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new Xe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var r;let{width:e,height:t}=((r=this.cameraTrack)==null?void 0:r.settings)||{};return bt(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Xe({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(Nl<=22),this._glVideoContext.on(Be.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,t,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),oe.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ft||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:r,error:t}):v.addSuccessEvent({key:r})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new 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}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Zc(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Be.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(r,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:s,player:n}=r;Ft&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return p(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),et===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Wt?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Wt?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new Yc(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ue.RENDER,l=>{var u;(u=this.cameraTrack)==null||u.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,c=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new kd(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Gt(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new gs(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;else if(this.waterMarkNode){let{width:c,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(c,l),c&&l&&this.waterMarkNode.resize(c,l)}(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"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.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)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,s,n,a;if(e instanceof Pt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof je)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof Oi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let c=e.mediaTrack;return e.setOutputMediaStreamTrack(c)}if(e instanceof go)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var t;e instanceof Pt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof je?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Oi?e.source&&e.source.context.destroy():e instanceof go&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return p(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return p(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let s=r.getContext("2d");if(!s)throw new D({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:u,fillVideo:m})=>{let h=m&&e||l,_=m&&t||u,g=m?0:a,E=m?0:c;s.drawImage(n,g,E,h,_)}),Bo(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return p(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return p(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return p(this,null,function*(){let t;try{t=yield Bo((e==null?void 0:e.imageElement)||e.imageUrl)}catch(h){throw new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:s=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2,fillVideo:u=!1}=e;this.watermarkImageList.some(h=>h.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(h=>h.type!==c),this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:u}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:u}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(h,_)=>h==="imageUrl"?void 0:_))})}deleteWatermark(e="watermark"){return p(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return p(this,null,function*(){var t,r,s;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 Bo(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(r=e.enableEffectOptimization)!=null?r:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}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 D({code:I.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._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return p(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new wd(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};M([Oc(function(e){this.log.error("update failed",e)}),Q(e=>function(...t){return p(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield y_,this.updated=new Promise((r,s)=>{e.apply(this,t).then(r,s),setTimeout(s,5e3,new D({code:I.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],sa.prototype,"update",1);var EI=0;var Ld=class extends J{constructor(e){super("room");d(this,"seq",++EI);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localPublishFlag",0);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"smallMode","canvas");d(this,"enableChorus",!1);d(this,"_isUsingCachedSchedule",!1);d(this,"_log");d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"heartbeatCount",0);d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this._log=R.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,he(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),he(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),he(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new I_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new A_({room:this}),this.badCaseDetector=new C_({room:this}),this.audioManager=new td(this),this.videoManager=new sa(this)}get videoCodec(){return"h264"}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 localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}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}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return p(this,null,function*(){return this.publish(e)})}removeTrack(e){return p(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return p(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(ie(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(dt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(dd([a,a]),Fr(`https://${a}`)):(s&&Fr(s),n&&dd(n))}S.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Pi.main,sched_back_domain:Pi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return p(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return p(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let s=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=s.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new D({code:I.INVALID_OPERATION,message:H({key:F.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Je.INVALID_DESTROY),new D({code:I.INVALID_OPERATION,message:H({key:F.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,S.emit(C.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var s,n,a,c;let r=U();try{let{isCached:l,result:u,detailCost:m}=yield bh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:He,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${_t(u,{keysToExclude:["username","credential"]})}`),l&&S.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=O(O({},this.scheduleResult),u),z((s=u.config)==null?void 0:s.retryCount)&&el(u.config.retryCount),ie((n=u.config)==null?void 0:n.loggerDomain)&&Fr(u.config.loggerDomain),this.videoDecodeFallbackType=((a=u.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=u.config)==null?void 0:c.smallMode)||this.smallMode,S.emit(C.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:m}),v.addSuccessEvent({key:521700,cost:U()-r})}catch(l){throw v.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var L_=Ge(at());var am=Ge(Zh());var v_=o=>{let i=De(o),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var s;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((s=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function N_(o){var e;let i=[];for(let t=0;t<o.rtp.length;t++){if(["rtx","red","ulpfec"].includes(o.rtp[t].codec))continue;let r=o.fmtp.filter(s=>s.payload===o.rtp[t].payload)[0];i.push({payload:o.rtp[t].payload,codec:o.rtp[t].codec,fmtp:r?r.config:"",rate:o.rtp[t].rate,rtx:((e=o.rtp[t+1])==null?void 0:e.codec)==="rtx"?o.rtp[t+1].payload:0,rtcpfb:((o==null?void 0:o.rtcpFb)||[]).filter(s=>s.payload===o.rtp[t].payload).map(({type:s,subtype:n})=>({id:s,params:n?[n]:[]}))})}return i}function SI(){return p(this,null,function*(){let o=new RTCPeerConnection;o.addTransceiver(f.VIDEO,{direction:f.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield o.createOffer();if(!i.sdp)return[];let e=De(i.sdp),t=N_(e.media[0]);return o.close(),t})}var D_=(o,i)=>p(void 0,null,function*(){var a;let e=De(o),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],s=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(c=>({id:c.value,uri:c.uri}))),s.ext&&(t.video.extensions=s.ext.map(c=>({id:c.value,uri:c.uri})));for(let c of r.rtp){if(c.codec!=="opus")continue;let l=r.fmtp.find(m=>m.payload===c.payload);if(!l)continue;let u={codec:c.codec,fmtp:l.config,payload:l.payload,rate:c.rate,channels:c.encoding,rtcpfb:[],rtx:0};(a=r.rtcpFb)==null||a.forEach(({payload:m,type:h,subtype:_})=>{if(m===u.payload){let g={id:h,params:[]};_&&g.params.push(_),u.rtcpfb.push(g)}}),t.audio.codecs.push(u);break}let n=["h264","vp8","h265"];return i&&n.shift(),t.video.codecs=[...N_(s)].filter(c=>n.includes(c.codec.toLocaleLowerCase())),t.video.decoders=(yield SI()).filter(c=>["h264","vp8","h265"].includes(c.codec.toLocaleLowerCase())),t}),M_=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=De(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:o.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:f.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[{payload:o.audio.codecs[0].payload,config:o.audio.codecs[0].fmtp}],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:"0",payloads:String(o.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:f.AUDIO,setup:o.dtls.setup,rtcpFb:o.audio.codecs[0].rtcpfb.map(a=>({payload:o.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:o.audio.codecs[0].payload,codec:o.audio.codecs[0].codec,rate:o.audio.codecs[0].rate,encoding:o.audio.codecs[0].channels}]};return s.media.push(n),[1,2,3].forEach(a=>{s.media.push(cm({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),Jt(s)},cm=({mid:o,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let s={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:f.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(o),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:f.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Vr(s,a)})}else{let n;i.useH265?n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()==="h265"):n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let a=i.video.codecs[n]||e.video.codecs[0];Vr(s,a)}return s},Vr=(o,i)=>{o.payloads=`${o.payloads} ${i.payload}`.trim(),o.fmtp.push({payload:i.payload,config:i.fmtp}),o.rtcpFb=[...o.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],o.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(o.payloads=`${o.payloads} ${i.rtx}`,o.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),o.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function II(o){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"]);o.ext&&(o.ext=o.ext.filter(e=>!i.has(e.uri)))}function AI(o){if(!o.rtcpFb)return;let i=[];o.rtcpFb.forEach((e,t)=>{var r;i.push(e),o.rtcpFb&&((r=o.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),o.rtcpFb=i}function CI(o){o.type===f.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function RI(o){o.type===f.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var O_=(o,i,e)=>{let t=am.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===f.AUDIO||r.type===f.VIDEO)&&(AI(r),CI(r),RI(r),II(r),r.type===f.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Vr(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>Vr(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),am.default.write(t)};var k_=Ge(at());var xd=class extends k_.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!_e&&$e&&S.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:s}){if(!(e||t===7||s!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(xd,"EVENT_BAD_HEALTH","bad_health");var P_=xd;var Li=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(Li||{}),x_=0,U_=!1,yI=new Set,bI=o=>x_>2&&!U_&&yI.size===0&&o,vI=1,jt=class extends L_.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"isDestroyed",!1);d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearWaitForConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);d(this,"originOffer",null);d(this,"autoSubscribedSsrcGroups",new Map);d(this,"autoSubscribedUserMap",new Map);d(this,"_h265DecodeFailed",!1);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=R.createLogger({parent:this._room.getLogger(),id:`spc${vI++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(hi?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destroy"),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 isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var t,r,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useH265?"h265":(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,r;return(e=this._serverAbility)!=null&&e.useH265&&((t=this._serverAbility)!=null&&t.video.decoders.find(s=>s.codec.toLowerCase()==="h265"))&&!this._h265DecodeFailed?"h265":(r=this._serverAbility)!=null&&r.video.decoders.find(s=>s.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?v_(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(){ss&&(this.scriptTransformWorker=ud({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"?this.emit("sei-message",e.data):e.data.type,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var s;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(s=this._peerConnection)==null?void 0:s.getConfiguration().encodedInsertableStreams;return wa(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return p(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),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._signalChannel.clearBakRelayIps(),v.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&v.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let s=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[s==="closed"?"debug":"info"](`signaling state: ${s}`)},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 n=new lm(s.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(f.AUDIO,{direction:f.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:f.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:f.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:f.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield D_(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,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}
118
+ offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return p(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e,(r,s)=>r==="username"||r==="credential"?"hided":s)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let s=r.getParameters();s.encodings[0]&&(s.encodings[0].priority=e,s.encodings[0].networkPriority=e,r.setParameters(s).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return p(this,null,function*(){var r,s,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=U(),c={type:"answer",sdp:M_({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(c),yield this.waitForPeerConnectionConnected();let l=((s=this._room.scheduleResult.config)==null?void 0:s.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||v.addSuccessEvent({key:521703,cost:U()-a})}catch(a){let c=a instanceof D&&a.code===I.API_CALL_ABORTED;throw c||this._log.error(`connect failed: ${a}`,e),this.reset(),!c&&!this.isReconnecting&&!this.isDestroyed&&(v.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return p(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(Se.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=O({ability:t},e),s=yield this._signalChannel.sendWaitForResponse({command:Y.REBUILD_PEER_CONNECTION,responseCommand:G.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new D({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(C.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting||this.isDestroyed)return;if(e!=null&&e.message.includes("timeout")){let t=Zt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ke(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),v.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Hi()&&this._log.warn(`SDK has tried reconnect for ${Hi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return p(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Se.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Ce.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var s;let t=((s=this._peerConnection)==null?void 0:s.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===Ce.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Ce.FAILED||e.target.connectionState===Ce.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Ce.CONNECTED||e.target.connectionState===Ce.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(C.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 Qt;let e=null;return!Rr()||this._peerConnection.getSenders().length===0?Qt:(e=this._peerConnection.getSenders()[0].transport,!oo()||this._peerConnection.getReceivers().length===0?Qt:e?e.state:Qt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Li.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Cr(r)){let s=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);s&&(this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.relayProtocol?`relayProtocol:${s.relayProtocol} url: ${s.url}`:""}`),s.networkType&&va(s.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(C.LEAVE_SUCCESS,s,this),this.off(Li.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});x_+=1,bI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),U_=!0,this.emit(Li.FIREWALL_RESTRICTION)),t(c)},Bs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(C.LEAVE_SUCCESS,s,this),this.on(Li.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return p(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let s=this._peerConnection.getTransceivers().slice(4).filter(h=>h.direction==="inactive").slice(0,3).map(h=>(h.direction=f.TRANSCEIVER_DIRECTION_RECVONLY,Number(h.mid)));this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(h=>{var _;return(_=h.ssrcs)==null?void 0:_.find(g=>{var E;return(E=g.value)==null?void 0:E.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(s.length===3)a=this._parsedAnswer.media.find(h=>Number(h.mid)===Number(s[0])),c=this._parsedAnswer.media.find(h=>Number(h.mid)===Number(s[1])),l=this._parsedAnswer.media.find(h=>Number(h.mid)===Number(s[2]));else if(s.length===0){this._peerConnection.addTransceiver(f.AUDIO,{direction:f.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:f.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:f.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let h=cm({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:De(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(h)),l=JSON.parse(JSON.stringify(h)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=f.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${f.MAIN} ${u}-audio`}],c.direction=f.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${f.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${f.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=f.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${u}-aux${f.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${u}-aux${f.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${u}-aux${f.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(h=>h.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return p(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive",s.ssrcs=[],s.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(s=>this._downlinkMIDUserIDMap.delete(s)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:s,auxVideo:n}=e;try{if(Tn()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],m;l===0&&t?m=t:l===1&&r?m=r:l===2&&s?m=s:l===3&&n&&(m=n),m&&(yield this.setSenderMaxBitrate(u,m))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,s;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),(s=this._parsedAnswer.media[e])!=null&&s.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();if((!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited")delete r.encodings[0].maxBitrate;else{if(r.encodings[0].maxBitrate===t*1e3)return;r.encodings[0].maxBitrate=t*1e3}return e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:s}){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=K?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:K?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:K?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:K?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:K?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:K?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:K?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:K?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:K?s*1e3:s}]);let c={type:"offer",sdp:Jt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let s=e.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);let n=s.encodings[0].scaleResolutionDownBy;if(T(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}setDegradationPreference(e,t,r){if($e&&qe<83||ge&&nn(Tt,"12.1")||K&&qo<138)return;let s=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),s.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),s.degradationPreference=n,e.setParameters(s).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=Jt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,s)=>p(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
119
119
  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)}
120
- next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:h,stopped:m})=>({mid:l,currentDirection:u,direction:h,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===se.INACTIVE&&n===se.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===se.SENDONLY&&n===se.INACTIVE&&(this._parsedAnswer.media[s].direction=se.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Ne(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=D_(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Vr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&(c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e}`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Ai(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let c=Math.floor(s/r),l=(this._isRelayTried||c>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),v.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};O([xc("reconnect")],Xt.prototype,"startReconnection",1),O([gi(e=>e.userId)],Xt.prototype,"addDownlink",1),O([gi(e=>e)],Xt.prototype,"removeDownlink",1),O([ir(!0)],Xt.prototype,"updateSDP",1),O([Rt(521712,!1),Eo(10,0)],Xt.prototype,"setOffer",1),O([Rt(521713,!1),Eo(10,0)],Xt.prototype,"setAnswer",1),O([Tf()],Xt.prototype,"close",1);var dm=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},lm=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let s=e.getUint16(t+2),n=new dm(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},L_=new Set;function xt(){let o=Math.floor(Math.random()*4294967296);return L_.has(o)?xt():(L_.add(o),o)}var B_=Je(at());var bo=class extends B_.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({parent:this._room.getLogger(),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:(S.emit(A.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 um=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=R.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
120
+ next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:m,stopped:h})=>({mid:l,currentDirection:u,direction:m,stopped:h})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return p(this,null,function*(){if(!K||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===ne.INACTIVE&&n===ne.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===ne.SENDONLY&&n===ne.INACTIVE&&(this._parsedAnswer.media[s].direction=ne.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return De(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=O_(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return p(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===f.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Vr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===f.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===f.VIDEO){let c;e&&(c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e}`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Ii(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let c=Math.floor(s/r),l=(this._isRelayTried||c>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return p(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),v.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};M([Lc("reconnect")],jt.prototype,"startReconnection",1),M([_i(e=>e.userId)],jt.prototype,"addDownlink",1),M([_i(e=>e)],jt.prototype,"removeDownlink",1),M([ir(!0)],jt.prototype,"updateSDP",1),M([Rt(521712,!1),Eo(10,0)],jt.prototype,"setOffer",1),M([Rt(521713,!1),Eo(10,0)],jt.prototype,"setAnswer",1),M([Tf()],jt.prototype,"close",1);var dm=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},lm=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let s=e.getUint16(t+2),n=new dm(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},w_=new Set;function xt(){let o=Math.floor(Math.random()*4294967296);return w_.has(o)?xt():(w_.add(o),o)}var V_=Ge(at());var bo=class extends V_.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({parent:this._room.getLogger(),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:(S.emit(C.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 um=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=R.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
121
121
  const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
122
- `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!fn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(h=a.msg_down_stream_info)==null?void 0:h.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];c=(m=_==null?void 0:_.msg_video_status)==null?void 0:m.filter(g=>g.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new um;var xd=class extends bo{constructor(e){super(L(M({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||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){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${ai()} ${ni()}`),v.addEnum({key:521719,value:F_[n]})});else{this._checkPublishStateTimeoutId=re.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Vs),auxVideo:!!(this.flag&Fr)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return f(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var c,l,u,h,m,_,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),_e&&Zo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_PUBLISH,responseCommand:G.SPC_PUBLISH_RESULT,data:L(M({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((c=this.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(m=(h=this.localMainVideoTrack)==null?void 0:h.small)==null?void 0:m.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(_,g,E)=>{var k;let C=c[g].sender.replaceTrack(E);u.push(g),(k=this.singlePC)!=null&&k.enableInsertableStreams&&C.then(()=>this.createEncodedStreams(c[g].sender,_)),this.initSenderTransform(c[g].sender,_),l.push(C)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(se.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m,_;let h=this.getTrackByMediaType(t);if(!h||!h.encodeFrame)return u.enqueue(l);h.isAudio?u.enqueue(h.enableEncodeFrame?h.encodeFrame(l):l):u.enqueue((m=this.singlePC)!=null&&m.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265?h.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!ns)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!gc()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(se.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;v.addFailedEvent({key:u,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=$o(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(se.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(M({},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(se.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._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),bi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=(a.width||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),yr()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===se.INACTIVE&&(yield this.singlePC.setTransceiverDirection(se.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),yr()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Z.UPDATE_MUTE_STAT,responseCommand:G.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.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}))})}};O([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],xd.prototype,"unpublish",1);var F_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(F_||{}),hm=xd;function H_(o){return Object.keys(o).filter(i=>o[i])}var Ms=class extends bo{constructor(e){super(L(M({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ti(this._room,this),this.remoteVideoTrack=new ki(this._room,this),this.remoteAuxiliaryTrack=new Es(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,u;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${H_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),v.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),We&&qe<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${H_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_SUBSCRIBE,responseCommand:G.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new D({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!Sc)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(Q(n)||Q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Sc||!this.singlePC||!this._peerConnection||gt(e)&&gt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&gt(t)||!c&&gt(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};O([ir(),Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Ms.prototype,"subscribe",1),O([ir()],Ms.prototype,"unsubscribe",1),O([gi(()=>"jitter")],Ms.prototype,"setJitterBufferDelay",1);var $_=Ms;function W_(){return Y(o=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function G_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var J_=Je(at());function NI(){return Math.floor(Math.random()*16383)}var Vd=class Vd extends J_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(G.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||NI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Z.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.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(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Vd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ke(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Vd,"SEQ_INTERVAL",300);var Ud=Vd;var{isString:q_,isUndefined:vo,getNetworkType:DI,isEmpty:OI}=vt,Ei=class extends wd{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",ss);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new ra(this,this._log),this.userManager=new od(this.userId,this._log),this._version=$e,this.sdpSemantics=Mo,vo(e.sdpSemantics)?vi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${DI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=vo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&ss,!vo(e.enableSPC)&&ss&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new M_(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]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=aa(n,[]);S.emit(A.REMOTE_PUBLISH_STATE_CHANGED,M({room:this},s)),this.emit("remote-publish-state-changed",M({},s))}),this.joinParams=e,new Promise((s,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 D&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=U();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:U()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Xt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new D({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ie.SETUP_FAILED,h=>{this.clearJoinTimeout(),S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),s(h)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&ss&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ll(),netType:Jr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&pn()};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{s(new D({code:I.JOIN_ROOM_FAILED,message:H({key:B.JOIN_ROOM_TIMEOUT})}))},a),S.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Z.SPC_JOIN_ROOM:Z.JOIN_ROOM,n),this.signalChannel.once(G.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:_,data:g,tinyId:E}=h.data;S.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var C;(C=this.singlePC)==null||C.connect(L(M({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${_}`),s(new D({code:I.JOIN_ROOM_FAILED,extraCode:m,message:H({key:B.JOIN_ROOM_FAILED,data:{error:_,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(M({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),oe.logSuccessEvent({userId:this.userId,eventType:Ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(xi.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof hm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(xi.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ia&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),oe.logFailedEvent({userId:this.userId,eventType:Ze.REJOIN,error:e}),this.emit("error",new D({code:I.JOIN_ROOM_FAILED,message:H({key:B.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||r_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new bs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Ud(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Os({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Os.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Ie.CONNECTION_STATE_CHANGED,a=>{S.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,M({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ie.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(G.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(G.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(G.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(G.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(oe.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(G.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${_t(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(G.FALLBACK_CODEC,a=>f(this,null,function*(){var l,u,h,m,_;let c=a.data.data;((l=c.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((u=this.singlePC)==null?void 0:u.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(h=c.videoControlInfo)==null?void 0:h.enableH265Enc}`),v.addCount({key:513e3}),yield(m=this.singlePC)==null?void 0:m.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Ie.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||Le(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Z.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Ef(this.userId):[],s=L(M({str_sdk_version:Ls,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:M({uint32_terminal_type:15,str_device_name:ni(),str_os_version:"",uint32_net_type:Jr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(A.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Z.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(M({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Qd).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",n)));let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof ia&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?$_:tm)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(M({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Z.GET_USER_LIST,responseCommand:G.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw H({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.USER_LIST_RES,code:r,message:s}})}):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||!zh)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)===Re.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof pt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Re.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),oe.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new tm({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new D({code:I.INVALID_OPERATION,message:H({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Z.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:G.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new D({code:I.SWITCH_ROLE_FAILED,message:H({key:B.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof D&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new D({code:I.SWITCH_ROLE_FAILED,message:H({key:B.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new hm({userId:this.userId,tinyId:this.tinyId,room:this}):new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",L(M({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return f(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof Xe?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return f(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof Xe?e:null})}catch(t){}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():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!nu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=M({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(A.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${vd(n)}] prev: [${vd(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof D?n.getCode():I.UNKNOWN,c=n;throw n instanceof D?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new D({code:I.API_CALL_ABORTED,message:H({key:B.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new D({code:a,message:H({key:B.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!au||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;Q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(vt.getTurnServer(s))):vt.isPlainObject(e)&&r.push(vt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.START_PUBLISH_TENCENT_CDN:Z.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.START_PUBLISH_TENCENT_CDN_RES:G.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.STOP_PUBLISH_TENCENT_CDN:Z.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.STOP_PUBLISH_TENCENT_CDN_RES:G.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Z.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:G.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=vt.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.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)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(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${ko-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=ko}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${ko-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ko};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(q_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!vo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new D({code:I.INVALID_PARAMETER,message:H({key:B.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(!vo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!vo(e.userDefinePushArgs))if(q_(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 D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_USER_DEFINE_PUSH_ARGS})});OI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&mi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new D({code:I.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}switchRoom(e){return f(this,null,function*(){var _;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((_=this.scheduleResult.config)==null?void 0:_.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let h=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ke(5e3).then(g)}),S.emit(A.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let m;try{this.userManager.clear(),m=yield this.signalChannel.sendWaitForResponse({command:Z.SWITCH_ROOM,responseCommand:G.SEND_SWITCH_ROOM_RES,data:u});let{code:g,message:E}=m.data;if(g===0)this.userSig=s,vo(n)||(this.privateMapKey=n),S.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:h,targetRoomId:c});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let C=new D({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(A.SWITCH_ROOM_FAILED,{room:this,error:C}),C}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=h,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),da(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_NETWORK_TIME,responseCommand:G.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};O([ye(["left",q.INIT],"joined"),Ot({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Lt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),Zf()],Ei.prototype,"join",1),O([ye("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Kf(),xc("leave room"),yn({fnName:"publish",validateArgs:!1}),yn({fnName:"unsubscribe",validateArgs:!1})],Ei.prototype,"leave",1),O([gi(e=>e.mediaType),W_(),Ot({settings:{retries:Hi,timeout:e=>Kt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(A.PUBLISH_FAILED,{room:this}))}})],Ei.prototype,"publish",1),O([yn({fnName:"publish"}),gi(e=>e.mediaType),G_(),Ct(function(){var e,t;this.localTracks.size===0&&Rr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ei.prototype,"unpublish",1),O([kc(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),gi(e=>e.userId)],Ei.prototype,"replaceTrack",1),O([gi((...e)=>e[0].userId),Eo(),e_(),Ot({settings:{retries:Hi,timeout:e=>Kt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],Ei.prototype,"subscribe",1),O([yn({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),gi((...e)=>e[0].userId)],Ei.prototype,"unsubscribe",1);ea.create=ea._create.bind(ea,Ei);hu(30);var w4=ea;export{w4 as default};
122
+ `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!fn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,m,h;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(m=a.msg_down_stream_info)==null?void 0:m.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];c=(h=_==null?void 0:_.msg_video_status)==null?void 0:h.filter(g=>g.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new um;var Ud=class extends bo{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||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){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${ni()} ${si()}`),v.addEnum({key:521719,value:F_[n]})});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Vs),auxVideo:!!(this.flag&Br)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return p(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var c,l,u,m,h,_,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),_e&&Yo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:G.SPC_PUBLISH_RESULT,data:L(O({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((c=this.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(h=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:h.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],m=(_,g,E)=>{var k;let A=c[g].sender.replaceTrack(E);u.push(g),(k=this.singlePC)!=null&&k.enableInsertableStreams&&A.then(()=>this.createEncodedStreams(c[g].sender,_)),this.initSenderTransform(c[g].sender,_),l.push(A)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let h=this.singlePC.setTransceiverDirection(ne.SENDONLY,u);return l.push(h),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var h,_;let m=this.getTrackByMediaType(t);if(!m||!m.encodeFrame)return u.enqueue(l);m.isAudio?u.enqueue(m.enableEncodeFrame?m.encodeFrame(l):l):u.enqueue((h=this.singlePC)!=null&&h.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265?m.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!ss)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return p(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!gc()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;v.addFailedEvent({key:u,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=Ho(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return p(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},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(ne.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),yi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=(a.width||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?f.AUXILIARY:f.MAIN} stream`),yr()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?f.AUXILIARY:f.MAIN} stream`),yr()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?f.AUXILIARY:f.MAIN} stream`),r.kind===f.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===f.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===f.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:G.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=f.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===f.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===f.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===f.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===f.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(Je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};M([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],Ud.prototype,"unpublish",1);var F_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(F_||{}),hm=Ud;function B_(o){return Object.keys(o).filter(i=>o[i])}var Os=class extends bo{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new gi(this._room,this),this.remoteVideoTrack=new Oi(this._room,this),this.remoteAuxiliaryTrack=new Es(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}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 Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.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===f.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,m;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=f.AUDIO;r.kind===f.VIDEO&&(c=a===f.MAIN?f.VIDEO:f.AUXILIARY);let l=this.remoteAudioTrack;c===f.VIDEO?l=this.remoteVideoTrack:c===f.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===f.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,u;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return p(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${B_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),v.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),$e&&qe<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${B_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:F.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return p(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:G.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new D({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!Sc)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(z(n)||z(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return p(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Sc||!this.singlePC||!this._peerConnection||gt(e)&&gt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return z(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),z(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var m;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&gt(t)||!c&&gt(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};M([ir(),Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Os.prototype,"subscribe",1),M([ir()],Os.prototype,"unsubscribe",1),M([_i(()=>"jitter")],Os.prototype,"setJitterBufferDelay",1);var H_=Os;function $_(){return Q(o=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function W_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var G_=Ge(at());function DI(){return Math.floor(Math.random()*16383)}var Fd=class Fd extends G_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(G.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||DI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.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(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Fd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ke(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Fd,"SEQ_INTERVAL",300);var Vd=Fd;var{isString:q_,isUndefined:vo,getNetworkType:MI,isEmpty:OI}=vt,Ti=class extends Ld{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",os);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new ra(this,this._log),this.userManager=new od(this.userId,this._log),this._version=He,this.sdpSemantics=Mo,vo(e.sdpSemantics)?bi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${MI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=vo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&os,!vo(e.enableSPC)&&os&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new P_(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]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=aa(n,[]);S.emit(C.REMOTE_PUBLISH_STATE_CHANGED,O({room:this},s)),this.emit("remote-publish-state-changed",O({},s))}),this.joinParams=e,new Promise((s,n)=>p(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 D&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=U();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:U()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new jt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new D({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>p(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Se.SETUP_FAILED,m=>{this.clearJoinTimeout(),S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),s(m)}),he((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&os&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ll(),netType:qr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&pn()};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{s(new D({code:I.JOIN_ROOM_FAILED,message:H({key:F.JOIN_ROOM_TIMEOUT})}))},a),S.emit(C.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(G.JOIN_ROOM_RESULT,m=>p(this,null,function*(){this.clearJoinTimeout();let{code:h,message:_,data:g,tinyId:E}=m.data;S.emit(C.JOIN_RECEIVED_CMD_RES,{room:this,code:h}),h===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var A;(A=this.singlePC)==null||A.connect(L(O({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${h} error: ${_}`),s(new D({code:I.JOIN_ROOM_FAILED,extraCode:h,message:H({key:F.JOIN_ROOM_FAILED,data:{error:_,code:h}})})))}))}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(O({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),se.logSuccessEvent({userId:this.userId,eventType:Ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Li.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof hm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Li.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ia&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),se.logFailedEvent({userId:this.userId,eventType:Ze.REJOIN,error:e}),this.emit("error",new D({code:I.JOIN_ROOM_FAILED,message:H({key:F.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||s_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new bs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Vd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ms({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ms.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Se.CONNECTION_STATE_CHANGED,a=>{S.emit(C.SIGNAL_CONNECTION_STATE_CHANGED,O({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Se.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(G.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(G.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(G.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(G.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(se.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(G.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${_t(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(G.FALLBACK_CODEC,a=>p(this,null,function*(){var l,u,m,h,_;let c=a.data.data;((l=c.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((u=this.singlePC)==null?void 0:u.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(m=c.videoControlInfo)==null?void 0:m.enableH265Enc}`),v.addCount({key:513e3}),yield(h=this.singlePC)==null?void 0:h.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Se.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(C.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||Le(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(C.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Ef(this.userId):[],s=L(O({str_sdk_version:Ls,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:O({uint32_terminal_type:15,str_device_name:si(),str_os_version:"",uint32_net_type:qr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(C.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(O({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Qd).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",n)));let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(C.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof ia&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?H_:tm)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(O({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:G.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.USER_LIST_RES,code:r,message:s}})}):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||!zh)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)===Ce.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof pt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Ce.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),se.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new tm({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new D({code:I.INVALID_OPERATION,message:H({key:F.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:G.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new D({code:I.SWITCH_ROLE_FAILED,message:H({key:F.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof D&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new D({code:I.SWITCH_ROLE_FAILED,message:H({key:F.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new hm({userId:this.userId,tinyId:this.tinyId,room:this}):new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",L(O({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return p(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return p(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null})}catch(t){}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():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!nu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(C.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:f.VIDEO,videoType:f.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=O({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(C.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${Nd(n)}] prev: [${Nd(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(C.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof D?n.getCode():I.UNKNOWN,c=n;throw n instanceof D?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new D({code:I.API_CALL_ABORTED,message:H({key:F.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new D({code:a,message:H({key:F.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(C.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(C.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return p(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!au||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;z(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&z(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return p(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return p(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(vt.getTurnServer(s))):vt.isPlainObject(e)&&r.push(vt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.START_PUBLISH_TENCENT_CDN_RES:G.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.STOP_PUBLISH_TENCENT_CDN_RES:G.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:G.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=vt.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.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)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(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Oo-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Oo}catch(m){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Oo-a.reSubscribeCount}. reason: ${m}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Oo};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(q_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!vo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.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(!vo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!vo(e.userDefinePushArgs))if(q_(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 D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_USER_DEFINE_PUSH_ARGS})});OI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return p(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&hi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new D({code:I.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}switchRoom(e){return p(this,null,function*(){var _;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((_=this.scheduleResult.config)==null?void 0:_.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let m=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ke(5e3).then(g)}),S.emit(C.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let h;try{this.userManager.clear(),h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:G.SEND_SWITCH_ROOM_RES,data:u});let{code:g,message:E}=h.data;if(g===0)this.userSig=s,vo(n)||(this.privateMapKey=n),S.emit(C.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:m,targetRoomId:c});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let A=new D({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(C.SWITCH_ROOM_FAILED,{room:this,error:A}),A}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=m,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),da(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_NETWORK_TIME,responseCommand:G.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};M([ye(["left",J.INIT],"joined"),Mt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Lt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),e_()],Ti.prototype,"join",1),M([ye("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),t_(),Lc("leave room"),yn({fnName:"publish",validateArgs:!1}),yn({fnName:"unsubscribe",validateArgs:!1})],Ti.prototype,"leave",1),M([_i(e=>e.mediaType),$_(),Mt({settings:{retries:Hi,timeout:e=>Zt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(C.PUBLISH_FAILED,{room:this}))}})],Ti.prototype,"publish",1),M([yn({fnName:"publish"}),_i(e=>e.mediaType),W_(),Ct(function(){var e,t;this.localTracks.size===0&&Rr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ti.prototype,"unpublish",1),M([Oc(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),_i(e=>e.userId)],Ti.prototype,"replaceTrack",1),M([_i((...e)=>e[0].userId),Eo(),i_(),Mt({settings:{retries:Hi,timeout:e=>Zt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(C.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],Ti.prototype,"subscribe",1),M([yn({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),_i((...e)=>e[0].userId)],Ti.prototype,"unsubscribe",1);ea.create=ea._create.bind(ea,Ti);hu(30);var H4=ea;export{H4 as default};