trtc-sdk-v5 5.8.5-ktv.2 → 5.8.5-ktv.21
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/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/chorus.esm.js +19 -17
- package/plugins/chorus/chorus.iife.js +19 -17
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/cross-room.esm.js +1 -1
- package/plugins/cross-room/cross-room.iife.js +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.js +4 -4
- package/plugins/device-detector/device-detector.iife.js +4 -4
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +2 -2
- package/plugins/video-effect/basic-beauty/basic-beauty.iife.js +2 -2
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/video-effect/watermark/watermark.esm.js +1 -1
- package/plugins/video-effect/watermark/watermark.iife.js +1 -1
- package/trtc.esm.js +33 -33
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Gm=Object.create;var Rs=Object.defineProperty,Wm=Object.defineProperties,Uu=Object.getOwnPropertyDescriptor,Jm=Object.getOwnPropertyDescriptors,jm=Object.getOwnPropertyNames,Wo=Object.getOwnPropertySymbols,Vu=Object.getPrototypeOf,Va=Object.prototype.hasOwnProperty,Bu=Object.prototype.propertyIsEnumerable,qm=Reflect.get;var Cs=Math.pow,Ua=(r,i,e)=>i in r?Rs(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,D=(r,i)=>{for(var e in i||(i={}))Va.call(i,e)&&Ua(r,e,i[e]);if(Wo)for(var e of Wo(i))Bu.call(i,e)&&Ua(r,e,i[e]);return r},w=(r,i)=>Wm(r,Jm(i));var Fu=(r,i)=>{var e={};for(var t in r)Va.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&Wo)for(var t of Wo(r))i.indexOf(t)<0&&Bu.call(r,t)&&(e[t]=r[t]);return e};var si=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),vr=(r,i)=>{for(var e in i)Rs(r,e,{get:i[e],enumerable:!0})},Xm=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of jm(i))!Va.call(r,s)&&s!==e&&Rs(r,s,{get:()=>i[s],enumerable:!(t=Uu(i,s))||t.enumerable});return r};var Ce=(r,i,e)=>(e=r!=null?Gm(Vu(r)):{},Xm(i||!r||!r.__esModule?Rs(e,"default",{value:r,enumerable:!0}):e,r));var N=(r,i,e,t)=>{for(var s=t>1?void 0:t?Uu(i,e):i,o=r.length-1,n;o>=0;o--)(n=r[o])&&(s=(t?n(i,e,s):n(s))||s);return t&&s&&Rs(i,e,s),s};var u=(r,i,e)=>(Ua(r,typeof i!="symbol"?i+"":i,e),e);var ye=(r,i,e)=>qm(Vu(r),e,i);var f=(r,i,e)=>new Promise((t,s)=>{var o=d=>{try{a(e.next(d))}catch(c){s(c)}},n=d=>{try{a(e.throw(d))}catch(c){s(c)}},a=d=>d.done?t(d.value):Promise.resolve(d.value).then(o,n);a((e=e.apply(r,i)).next())});var Pe=si((ug,Ba)=>{"use strict";var Qm=Object.prototype.hasOwnProperty,Fe="~";function ys(){}Object.create&&(ys.prototype=Object.create(null),new ys().__proto__||(Fe=!1));function zm(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function $u(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new zm(e,t||r,s),n=Fe?Fe+i:i;return r._events[n]?r._events[n].fn?r._events[n]=[r._events[n],o]:r._events[n].push(o):(r._events[n]=o,r._eventsCount++),r}function Jo(r,i){--r._eventsCount===0?r._events=new ys:delete r._events[i]}function ke(){this._events=new ys,this._eventsCount=0}ke.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Qm.call(e,t)&&i.push(Fe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};ke.prototype.listeners=function(i){var e=Fe?Fe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,o=t.length,n=new Array(o);s<o;s++)n[s]=t[s].fn;return n};ke.prototype.listenerCount=function(i){var e=Fe?Fe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};ke.prototype.emit=function(i,e,t,s,o,n){var a=Fe?Fe+i:i;if(!this._events[a])return!1;var d=this._events[a],c=arguments.length,l,m;if(d.fn){switch(d.once&&this.removeListener(i,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,t),!0;case 4:return d.fn.call(d.context,e,t,s),!0;case 5:return d.fn.call(d.context,e,t,s,o),!0;case 6:return d.fn.call(d.context,e,t,s,o,n),!0}for(m=1,l=new Array(c-1);m<c;m++)l[m-1]=arguments[m];d.fn.apply(d.context,l)}else{var p=d.length,_;for(m=0;m<p;m++)switch(d[m].once&&this.removeListener(i,d[m].fn,void 0,!0),c){case 1:d[m].fn.call(d[m].context);break;case 2:d[m].fn.call(d[m].context,e);break;case 3:d[m].fn.call(d[m].context,e,t);break;case 4:d[m].fn.call(d[m].context,e,t,s);break;default:if(!l)for(_=1,l=new Array(c-1);_<c;_++)l[_-1]=arguments[_];d[m].fn.apply(d[m].context,l)}}return!0};ke.prototype.on=function(i,e,t){return $u(this,i,e,t,!1)};ke.prototype.once=function(i,e,t){return $u(this,i,e,t,!0)};ke.prototype.removeListener=function(i,e,t,s){var o=Fe?Fe+i:i;if(!this._events[o])return this;if(!e)return Jo(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!s||n.once)&&(!t||n.context===t)&&Jo(this,o);else{for(var a=0,d=[],c=n.length;a<c;a++)(n[a].fn!==e||s&&!n[a].once||t&&n[a].context!==t)&&d.push(n[a]);d.length?this._events[o]=d.length===1?d[0]:d:Jo(this,o)}return this};ke.prototype.removeAllListeners=function(i){var e;return i?(e=Fe?Fe+i:i,this._events[e]&&Jo(this,e)):(this._events=new ys,this._eventsCount=0),this};ke.prototype.off=ke.prototype.removeListener;ke.prototype.addListener=ke.prototype.on;ke.prefixed=Fe;ke.EventEmitter=ke;typeof Ba!="undefined"&&(Ba.exports=ke)});var Lc=si((OE,yl)=>{var Cl=yl.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Cl).forEach(function(r){var i=Cl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var vl=si(gi=>{var Kr=function(r){return String(Number(r))===r?Number(r):r},cf=function(r,i,e,t){if(t&&!e)i[t]=Kr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Kr(r[s+1]))},df=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;cf(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},bl=Lc(),uf=RegExp.prototype.test.bind(/^([a-z])=(.*)/);gi.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(uf).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(bl[o]||[]).length;a+=1){var d=bl[o][a];if(d.reg.test(n))return df(d,t,n)}}),i.media=e,i};var Nl=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Kr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};gi.parseParams=function(r){return r.split(/;\s?/).reduce(Nl,{})};gi.parseFmtpConfig=gi.parseParams;gi.parsePayloads=function(r){return r.toString().split(" ").map(Number)};gi.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Kr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};gi.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Nl,{})})};gi.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Kr(e):(t=Kr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Ol=si((kE,Dl)=>{var wc=Lc(),lf=/%[sdv%]/g,hf=function(r){var i=1,e=arguments,t=e.length;return r.replace(lf,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},so=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return hf.apply(null,s)},mf=["v","o","s","i","u","e","p","c","b","t","r","z","a"],pf=["i","c","b","a"];Dl.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||mf,t=i.innerOrder||pf,s=[];return e.forEach(function(o){wc[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(so(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(so(o,n,a))})})}),r.media.forEach(function(o){s.push(so("m",wc.m[0],o)),t.forEach(function(n){wc[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(so(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){s.push(so(n,a,d))})})})}),s.join(`\r
|
|
1
|
+
var Fm=Object.create;var Cs=Object.defineProperty,Hm=Object.defineProperties,Vu=Object.getOwnPropertyDescriptor,Gm=Object.getOwnPropertyDescriptors,Wm=Object.getOwnPropertyNames,Jo=Object.getOwnPropertySymbols,Bu=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty,$u=Object.prototype.propertyIsEnumerable,Jm=Reflect.get;var Rs=Math.pow,wa=(s,i,e)=>i in s?Cs(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,D=(s,i)=>{for(var e in i||(i={}))Ua.call(i,e)&&wa(s,e,i[e]);if(Jo)for(var e of Jo(i))$u.call(i,e)&&wa(s,e,i[e]);return s},x=(s,i)=>Hm(s,Gm(i));var Fu=(s,i)=>{var e={};for(var t in s)Ua.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&Jo)for(var t of Jo(s))i.indexOf(t)<0&&$u.call(s,t)&&(e[t]=s[t]);return e};var ii=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),vr=(s,i)=>{for(var e in i)Cs(s,e,{get:i[e],enumerable:!0})},jm=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Wm(i))!Ua.call(s,r)&&r!==e&&Cs(s,r,{get:()=>i[r],enumerable:!(t=Vu(i,r))||t.enumerable});return s};var ye=(s,i,e)=>(e=s!=null?Fm(Bu(s)):{},jm(i||!s||!s.__esModule?Cs(e,"default",{value:s,enumerable:!0}):e,s));var N=(s,i,e,t)=>{for(var r=t>1?void 0:t?Vu(i,e):i,o=s.length-1,n;o>=0;o--)(n=s[o])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Cs(i,e,r),r};var u=(s,i,e)=>(wa(s,typeof i!="symbol"?i+"":i,e),e);var Se=(s,i,e)=>Jm(Bu(s),e,i);var f=(s,i,e)=>new Promise((t,r)=>{var o=c=>{try{a(e.next(c))}catch(d){r(d)}},n=c=>{try{a(e.throw(c))}catch(d){r(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(s,i)).next())});var xe=ii((dE,Va)=>{"use strict";var qm=Object.prototype.hasOwnProperty,$e="~";function ys(){}Object.create&&(ys.prototype=Object.create(null),new ys().__proto__||($e=!1));function Xm(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function Hu(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new Xm(e,t||s,r),n=$e?$e+i:i;return s._events[n]?s._events[n].fn?s._events[n]=[s._events[n],o]:s._events[n].push(o):(s._events[n]=o,s._eventsCount++),s}function jo(s,i){--s._eventsCount===0?s._events=new ys:delete s._events[i]}function Le(){this._events=new ys,this._eventsCount=0}Le.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)qm.call(e,t)&&i.push($e?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Le.prototype.listeners=function(i){var e=$e?$e+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};Le.prototype.listenerCount=function(i){var e=$e?$e+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Le.prototype.emit=function(i,e,t,r,o,n){var a=$e?$e+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,l,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,o),!0;case 6:return c.fn.call(c.context,e,t,r,o,n),!0}for(m=1,l=new Array(d-1);m<d;m++)l[m-1]=arguments[m];c.fn.apply(c.context,l)}else{var p=c.length,_;for(m=0;m<p;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),d){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,e);break;case 3:c[m].fn.call(c[m].context,e,t);break;case 4:c[m].fn.call(c[m].context,e,t,r);break;default:if(!l)for(_=1,l=new Array(d-1);_<d;_++)l[_-1]=arguments[_];c[m].fn.apply(c[m].context,l)}}return!0};Le.prototype.on=function(i,e,t){return Hu(this,i,e,t,!1)};Le.prototype.once=function(i,e,t){return Hu(this,i,e,t,!0)};Le.prototype.removeListener=function(i,e,t,r){var o=$e?$e+i:i;if(!this._events[o])return this;if(!e)return jo(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&jo(this,o);else{for(var a=0,c=[],d=n.length;a<d;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:jo(this,o)}return this};Le.prototype.removeAllListeners=function(i){var e;return i?(e=$e?$e+i:i,this._events[e]&&jo(this,e)):(this._events=new ys,this._eventsCount=0),this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.addListener=Le.prototype.on;Le.prefixed=$e;Le.EventEmitter=Le;typeof Va!="undefined"&&(Va.exports=Le)});var wc=ii((Dg,bl)=>{var yl=bl.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(yl).forEach(function(s){var i=yl[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Dl=ii(fi=>{var Yr=function(s){return String(Number(s))===s?Number(s):s},nf=function(s,i,e,t){if(t&&!e)i[t]=Yr(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Yr(s[r+1]))},af=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;nf(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},Nl=wc(),cf=RegExp.prototype.test.bind(/^([a-z])=(.*)/);fi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(cf).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Nl[o]||[]).length;a+=1){var c=Nl[o][a];if(c.reg.test(n))return af(c,t,n)}}),i.media=e,i};var vl=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Yr(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};fi.parseParams=function(s){return s.split(/;\s?/).reduce(vl,{})};fi.parseFmtpConfig=fi.parseParams;fi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};fi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Yr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};fi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(vl,{})})};fi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Yr(e):(t=Yr(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Ml=ii((Mg,Ol)=>{var Uc=wc(),df=/%[sdv%]/g,uf=function(s){var i=1,e=arguments,t=e.length;return s.replace(df,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},oo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return uf.apply(null,r)},lf=["v","o","s","i","u","e","p","c","b","t","r","z","a"],hf=["i","c","b","a"];Ol.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||lf,t=i.innerOrder||hf,r=[];return e.forEach(function(o){Uc[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(oo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(oo(o,n,a))})})}),s.media.forEach(function(o){r.push(oo("m",Uc.m[0],o)),t.forEach(function(n){Uc[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(oo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(oo(n,a,c))})})})}),r.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var Ml=si(Ei=>{var cr=vl(),ff=Ol();Ei.write=ff;Ei.parse=cr.parse;Ei.parseParams=cr.parseParams;Ei.parseFmtpConfig=cr.parseFmtpConfig;Ei.parsePayloads=cr.parsePayloads;Ei.parseRemoteCandidates=cr.parseRemoteCandidates;Ei.parseImageAttributes=cr.parseImageAttributes;Ei.parseSimulcastStreamList=cr.parseSimulcastStreamList});var Eu=si((tk,Yh)=>{var zh=Yh.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(zh).forEach(function(r){var i=zh[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var em=si(Ni=>{var gs=function(r){return String(Number(r))===r?Number(r):r},w_=function(r,i,e,t){if(t&&!e)i[t]=gs(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=gs(r[s+1]))},x_=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;w_(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Kh=Eu(),U_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Ni.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(U_).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Kh[o]||[]).length;a+=1){var d=Kh[o][a];if(d.reg.test(n))return x_(d,t,n)}}),i.media=e,i};var Zh=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=gs(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};Ni.parseParams=function(r){return r.split(/;\s?/).reduce(Zh,{})};Ni.parseFmtpConfig=Ni.parseParams;Ni.parsePayloads=function(r){return r.toString().split(" ").map(Number)};Ni.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(gs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Ni.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Zh,{})})};Ni.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=gs(e):(t=gs(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var im=si((rk,tm)=>{var Tu=Eu(),V_=/%[sdv%]/g,B_=function(r){var i=1,e=arguments,t=e.length;return r.replace(V_,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Mo=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return B_.apply(null,s)},F_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],$_=["i","c","b","a"];tm.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||F_,t=i.innerOrder||$_,s=[];return e.forEach(function(o){Tu[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(Mo(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(Mo(o,n,a))})})}),r.media.forEach(function(o){s.push(Mo("m",Tu.m[0],o)),t.forEach(function(n){Tu[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(Mo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){s.push(Mo(n,a,d))})})})}),s.join(`\r
|
|
3
|
+
`}});var kl=ii(_i=>{var nr=Dl(),mf=Ml();_i.write=mf;_i.parse=nr.parse;_i.parseParams=nr.parseParams;_i.parseFmtpConfig=nr.parseFmtpConfig;_i.parsePayloads=nr.parsePayloads;_i.parseRemoteCandidates=nr.parseRemoteCandidates;_i.parseImageAttributes=nr.parseImageAttributes;_i.parseSimulcastStreamList=nr.parseSimulcastStreamList});var Tu=ii((ek,Qh)=>{var Xh=Qh.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Xh).forEach(function(s){var i=Xh[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Kh=ii(yi=>{var Es=function(s){return String(Number(s))===s?Number(s):s},L_=function(s,i,e,t){if(t&&!e)i[t]=Es(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Es(s[r+1]))},x_=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;L_(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},zh=Tu(),w_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);yi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(w_).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(zh[o]||[]).length;a+=1){var c=zh[o][a];if(c.reg.test(n))return x_(c,t,n)}}),i.media=e,i};var Yh=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Es(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};yi.parseParams=function(s){return s.split(/;\s?/).reduce(Yh,{})};yi.parseFmtpConfig=yi.parseParams;yi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};yi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Es),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};yi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Yh,{})})};yi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Es(e):(t=Es(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var em=ii((ik,Zh)=>{var Su=Tu(),U_=/%[sdv%]/g,V_=function(s){var i=1,e=arguments,t=e.length;return s.replace(U_,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},ko=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return V_.apply(null,r)},B_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],$_=["i","c","b","a"];Zh.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||B_,t=i.innerOrder||$_,r=[];return e.forEach(function(o){Su[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(ko(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(ko(o,n,a))})})}),s.media.forEach(function(o){r.push(ko("m",Su.m[0],o)),t.forEach(function(n){Su[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(ko(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(ko(n,a,c))})})})}),r.join(`\r
|
|
4
4
|
`)+`\r
|
|
5
|
-
`}});var Su=si(vi=>{var Rr=em(),H_=im();vi.write=H_;vi.parse=Rr.parse;vi.parseParams=Rr.parseParams;vi.parseFmtpConfig=Rr.parseFmtpConfig;vi.parsePayloads=Rr.parsePayloads;vi.parseRemoteCandidates=Rr.parseRemoteCandidates;vi.parseImageAttributes=Rr.parseImageAttributes;vi.parseSimulcastStreamList=Rr.parseSimulcastStreamList});import WU from"webrtc-adapter";var Hh=Ce(Pe());var Hu=(k=>(k[k.INVALID_PARAMETER=4096]="INVALID_PARAMETER",k[k.INVALID_OPERATION=4097]="INVALID_OPERATION",k[k.NOT_SUPPORTED=4098]="NOT_SUPPORTED",k[k.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",k[k.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",k[k.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",k[k.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",k[k.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",k[k.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",k[k.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",k[k.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",k[k.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",k[k.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",k[k.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",k[k.CLIENT_BANNED=16448]="CLIENT_BANNED",k[k.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",k[k.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",k[k.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",k[k.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",k[k.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",k[k.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",k[k.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",k[k.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",k[k.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",k[k.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",k[k.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",k[k.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",k[k.API_CALL_ABORTED=16461]="API_CALL_ABORTED",k[k.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",k[k.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",k[k.UNKNOWN=65535]="UNKNOWN",k))(Hu||{}),S=Hu;var Ym=function(r){for(let i in S)if(S[i]===r)return i;return"UNKNOWN"},Fa=class extends Error{constructor({name:e="RtcError",message:t,code:s=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${Ym(s)} 0x${s.toString(16)}>`,d=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(d);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=s,this.extraCode=o,this.name=e,this.message=d,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=Fa;var Wu=0,Gu=!0,Ju=function(r){Wu=r;let i=new Date;i.setTime(i.getTime()+r),y[Gu?"info":"debug"](`baseTime from server: ${i} offset: ${r}`),Gu=!1},$e=function(){return Date.now()+Wu},jo=function(){let r=new Date;return r.setTime($e()),r.toLocaleString()};var He={};vr(He,{bytes2ms:()=>Jp,concatArrayBuffers:()=>io,convertObjectNumberToInt:()=>bn,copyProperties:()=>Wp,deepClone:()=>Qr,deepMerge:()=>fi,delay:()=>Gi,fibonacci:()=>Xr,formatedTime:()=>ef,getAbilityConfigUrl:()=>_l,getConstructorName:()=>Cn,getContainerFromElement:()=>Kp,getEnv:()=>Gp,getFirst16Bits:()=>tf,getInternalVersion:()=>Qp,getLast16Bits:()=>_i,getLoggerUrl:()=>Fi,getMuteStateFromFlag:()=>Hi,getNetworkType:()=>Tl,getNumNetworkType:()=>zr,getReconnectionTimeout:()=>Ht,getStringByteLength:()=>yn,getTurnServer:()=>Yp,getUint32Version:()=>Oc,getValueType:()=>Se,getViewListFromView:()=>eo,glog:()=>Rl,ipv4ToUint32:()=>Zs,isArray:()=>_e,isAudioWorkletSupported:()=>Xp,isBoolean:()=>le,isConstructor:()=>Ks,isEmpty:()=>Nc,isFunction:()=>ie,isLangChinese:()=>Vt,isMediaStreamTrack:()=>qp,isNumber:()=>te,isObject:()=>bt,isOverseaSdkAppId:()=>Qs,isPlainObject:()=>et,isPortrait:()=>Dc,isPromise:()=>ar,isRemoteTrack:()=>vt,isString:()=>K,isUndefined:()=>E,loadImage:()=>to,ms2bytes:()=>jp,ms2samples:()=>Al,performanceNow:()=>P,promiseAny:()=>zs,samples2ms:()=>Il,setNetworkType:()=>bc,stringify:()=>Nt,stringifyIncludeValue:()=>vc,throttlePromise:()=>Mc});var ec={};vr(ec,{AUDIO_MUTE_BIT:()=>Ko,AUDIO_STAT_BIT:()=>Mi,AUX_STAT_BIT:()=>er,AUX_STREAM_MSID:()=>ja,BACKEND_ENV:()=>Yo,BASE_DOC_URL:()=>wt,BASE_HOST:()=>ju,CAPABILITIES_KEYS:()=>tn,CLASS_NAME:()=>Tp,CLOUD_CONSOLE_URL:()=>tp,CROSS_ROOM_BIT:()=>Ja,DATA_FREEZE_TIMING:()=>en,DOC_URL:()=>ip,DTLS_STATE_UNKNOWN:()=>ft,ENV_NAME:()=>oi,EXCHANGE_SDP_TIMEOUT:()=>Ya,INTERVAL:()=>rr,IS_WORKER:()=>Dr,IS_WORKLET:()=>Ns,KIBANA_EVENT:()=>We,LOCAL_STREAM_PUBLISH_STATE:()=>Qu,LOGGER_CMD_TYPE:()=>Di,LOGGER_DOMAIN:()=>Ha,LOGGER_DOMAIN_OVERSEA:()=>Ga,LOG_LEVEL:()=>pt,LOG_LEVEL_NAME:()=>Ip,MAIN_STREAM_MSID:()=>Os,MAX_RTT:()=>Ps,MICROPHONE_COMMUNICATIONS:()=>Sp,MICROPHONE_DEFAULT:()=>ir,MUTE_ALL_BIT:()=>op,NAME:()=>h,NETWORK_TYPE:()=>qo,NOT_SUPPORTED_H264:()=>tr,PAUSED_RETRY_COUNT:()=>Ka,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Ms,PEER_CONNECTION_STATE:()=>ne,PEER_LEAVE_REASON:()=>Za,RAF:()=>Pr,RECOVER_CAPTURE_INTERVAL:()=>kr,REMOTE_STREAM_TYPE_AUX:()=>Xa,REMOTE_STREAM_TYPE_MAIN:()=>qa,RENDER_FREEZE_TIMING:()=>fp,RIC:()=>Pi,SCHEDULE_DOMAIN:()=>_t,SCHEDULE_TIMEOUT:()=>Ep,SDP_SEMANTICS_PLAN_B:()=>Or,SDP_SEMANTICS_UNIFIED_PLAN:()=>ki,SECOND_HOST:()=>Zm,SIGNAL_PING_PONG_INTERVAL:()=>sp,SIGNAL_PING_TIMEOUT:()=>rp,SIGNAL_RECONNECTION_COUNT:()=>mp,SMALL_STAT_BIT:()=>Ds,SPEAKER_DEFAULT:()=>ks,STORAGE_EXPIRES_TIME:()=>Xo,STREAM_TYPE_BIG:()=>_p,STREAM_TYPE_SMALL:()=>gp,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Mr,SYNC_USER_LIST_INTERVAL:()=>pp,Scene:()=>xt,Switch:()=>qu,THIRD_HOST:()=>ep,TIMEOUT:()=>Li,TRANSPORT_DIRECTION:()=>Y,TRTC_ERROR_ASSISTANCE:()=>Wa,TRTC_QUALITY_BAD:()=>up,TRTC_QUALITY_DISCONNECTED:()=>hp,TRTC_QUALITY_EXCELLENT:()=>ap,TRTC_QUALITY_GOOD:()=>cp,TRTC_QUALITY_POOR:()=>dp,TRTC_QUALITY_UNKNOWN:()=>np,TRTC_QUALITY_VERY_BAD:()=>lp,UPDATE_OFFER_TIMEOUT:()=>za,VIDEO_MUTE_BIT:()=>Zo,VIDEO_STAT_BIT:()=>Oi,audioProfileMap:()=>Qo,getRetryCount:()=>ni,getScriptDir:()=>Km,innerVersion:()=>bs,loggerProxy:()=>vs,screenProfileMap:()=>zo,setLoggerProxy:()=>Zi,setRetryCount:()=>Qa,setVersion:()=>$a,version:()=>Te,videoProfileMap:()=>nt});var bs="4.15.00.1600",Te="5.0.0";function $a(r){Te=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));bs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Dr=typeof importScripts!="undefined",Ns=typeof registerProcessor!="undefined",Km=()=>{let r=Dr?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},vs="",Zi=r=>vs=r,ju="web.sdk.qcloud.com",Zm="web.sdk.tencent.cn",ep="web.sdk.cloud.tencent.cn",tp="https://console.cloud.tencent.com/trtc",wt=`https://${ju}/trtc/webrtc/v5/doc`,ip=`${wt}/zh-cn/`,Ha="https://yun.tim.qq.com",Ga="https://apisgp.my-imcloud.com",Wa="trtc_error_assistance",Di={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},oi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},pt=(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))(pt||{}),rp=18e3,sp=2e3,qo={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Xo=7*24*3600*1e3,qu=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(qu||{}),Qo={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}},nt={"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}},zo={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},h={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Y={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Yo={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},xt=(e=>(e.LIVE="live",e.RTC="rtc",e))(xt||{}),Oi=1,Ds=2,er=4,Mi=8,Ko=64,Zo=16,op=112,Ja=128,Os="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ja="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",qa=h.MAIN,Xa=h.AUXILIARY,np=0,ap=1,cp=2,dp=3,up=4,lp=5,hp=6,ft="unknown",ne={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Xu=1/0;function Qa(r){Xu=r}function ni(){return Xu}var mp=30,We={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"},pp=1e4,za=1e4,Ya=1e4,ki="unified-plan",Or="plan-b",tr=1028,Qu=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Qu||{}),en=500,fp=1e3,_p=h.BIG,gp=h.SMALL,Ms=10*1e3,_t={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},Ep=2e3,Tp={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Ka=5,ir="default",ks=ir,Sp="communications",Ip=Object.keys(pt),Za=["normal leave","timeout leave","kick","role change"],Mr=10,kr=2e3,Pi="ric",Pr="raf",rr="interval",Li="timeout",tn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Ps=10*1e3;function ai({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((o,n)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);o({data:a})}catch(a){o({data:s.response})}else n({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function tc(r){return f(this,null,function*(){let i=P(),e=JSON.stringify(r);try{if(!CompressionStream||e.length<=2800)return e;let s=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(s)).blob()).arrayBuffer();return y.debug(`compressJSON ${e.length} -> ${a.byteLength} ${P()-i}ms`),a}catch(t){return e}})}var dc={};vr(dc,{AUDIO_LEVEL_SCALE:()=>at,AudioCodecPipelineType:()=>on,AudioType:()=>Zu,BASIC_TYPE:()=>wr,BannedReason:()=>cc,CONNECTION_CLOSED_REASON:()=>rc,ClientEvent:()=>zu,ConnectionEvent:()=>gt,ConnectionState:()=>Ke,FacingMode:()=>rn,LeaveReason:()=>rl,LocalTrackEvent:()=>Ls,MULTI_VIDEO_DATA_TYPE:()=>Et,MediaType:()=>be,MediaTypeLabel:()=>Ap,MonitorEventId:()=>ws,MutedFlag:()=>Ku,NetworkQualityValue:()=>ac,PlayerState:()=>Lr,ReceiveMode:()=>il,RemoteStreamType:()=>Ze,RoomEvent:()=>wi,SceneNumber:()=>sc,StreamEvent:()=>Yu,StreamType:()=>tl,SubscribeMediaType:()=>ic,TRACK_ACTION:()=>nc,TRACK_KIND:()=>oc,TrackEvent:()=>xi,UserRole:()=>Le,UserRoleNumber:()=>sr,VideoCodec:()=>Ui,VideoCodecPipelineType:()=>sn,VideoType:()=>el});var gt=(A=>(A.TRACK_ADDED="track-added",A.TRACK_UPDATED="track-updated",A.TRACK_SUBSCRIBED="track-subscribed",A.STREAM_ADDED="stream-added",A.STREAM_REMOVED="stream-removed",A.STREAM_UPDATED="stream-updated",A.STREAM_PUBLISHED="stream-published",A.STREAM_SUBSCRIBED="stream-subscribed",A.STREAM_UNSUBSCRIBED="stream-unsubscribed",A.STATE_CHANGED="state-changed",A.ERROR="error",A.CONNECTION_STATE_CHANGED="connection-state-changed",A.FIREWALL_RESTRICTION="firewall-restriction",A.SEI_MESSAGE="sei-message",A.CLOSED="closed",A))(gt||{}),rc=(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))(rc||{}),zu=(R=>(R.STREAM_ADDED="stream-added",R.STREAM_REMOVED="stream-removed",R.STREAM_UPDATED="stream-updated",R.STREAM_SUBSCRIBED="stream-subscribed",R.CONNECTION_STATE_CHANGED="connection-state-changed",R.PEER_JOIN="peer-join",R.PEER_LEAVE="peer-leave",R.MUTE_AUDIO="mute-audio",R.MUTE_VIDEO="mute-video",R.UNMUTE_AUDIO="unmute-audio",R.UNMUTE_VIDEO="unmute-video",R.CLIENT_BANNED="client-banned",R.NETWORK_QUALITY="network-quality",R.AUDIO_VOLUME="audio-volume",R.SEI_MESSAGE="sei-message",R.ERROR="error",R))(zu||{}),Yu=(o=>(o.PLAYER_STATE_CHANGED="player-state-changed",o.SCREEN_SHARING_STOPPED="screen-sharing-stopped",o.CONNECTION_STATE_CHANGED="connection-state-changed",o.DEVICE_AUTO_RECOVERED="device-auto-recovered",o.ERROR="error",o))(Yu||{}),Ls=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(Ls||{}),Lr=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Lr||{}),wi=(R=>(R.PEER_JOIN="peer-join",R.PEER_LEAVE="peer-leave",R.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",R.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",R.BANNED="banned",R.NETWORK_QUALITY="network-quality",R.AUDIO_VOLUME="audio-volume",R.SEI_MESSAGE="sei-message",R.ERROR="error",R.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",R.REMOTE_PUBLISHED="remote-published",R.REMOTE_UNPUBLISHED="remote-unpublished",R.FIREWALL_RESTRICTION="firewall-restriction",R.HEARTBEAT_REPORT="heartbeat-report",R.CUSTOM_MESSAGE="custom-message",R.NTP_TIME_UPDATED="ntp-time-updated",R))(wi||{}),xi=(n=>(n.PLAYER_STATE_CHANGED="player-state-changed",n.MUTE="mute",n.UNMUTE="unmute",n.ERROR="error",n.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",n.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",n))(xi||{}),Ku=(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))(Ku||{}),sc=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(sc||{}),sr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(sr||{}),Le=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Le||{}),Ke=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(Ke||{}),oc=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(oc||{}),nc=(e=>(e.ADD="add",e.REMOVE="remove",e))(nc||{}),be=(o=>(o[o.NULL=0]="NULL",o[o.AUDIO=1]="AUDIO",o[o.AUX_VIDEO=2]="AUX_VIDEO",o[o.BIG_VIDEO=4]="BIG_VIDEO",o[o.SMALL_VIDEO=8]="SMALL_VIDEO",o))(be||{}),Ap={[1]:"audio",[2]:"auxVideo",[4]:"video"},Zu=(i=>(i[i.opus=111]="opus",i))(Zu||{}),el=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(el||{}),tl=(e=>(e.Big="big",e.Small="small",e))(tl||{}),Ze=(e=>(e.Main="main",e.Aux="auxiliary",e))(Ze||{}),Et=(o=>(o[o.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",o[o.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",o[o.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",o[o.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",o[o.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",o))(Et||{}),ws=(O=>(O[O.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",O[O.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",O[O.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",O[O.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",O[O.MUTE_AUDIO=32772]="MUTE_AUDIO",O[O.MUTE_VIDEO=32773]="MUTE_VIDEO",O[O.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",O[O.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",O[O.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",O[O.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",O[O.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",O[O.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",O[O.SWITCH_CAMERA=32780]="SWITCH_CAMERA",O[O.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",O[O.REPLACE_VIDEO=32782]="REPLACE_VIDEO",O[O.REPLACE_AUDIO=32783]="REPLACE_AUDIO",O[O.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",O[O.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",O[O.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",O[O.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",O[O.JOIN=32788]="JOIN",O[O.LEAVE=32789]="LEAVE",O[O.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",O[O.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",O[O.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",O[O.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",O[O.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",O[O.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",O[O.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",O[O.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",O[O.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",O[O.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",O[O.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",O[O.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",O[O.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",O[O.PUBLISH_AUX=32805]="PUBLISH_AUX",O[O.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",O[O.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",O[O.VIDEO_ENCODER=4004]="VIDEO_ENCODER",O[O.VIDEO_DECODER=4005]="VIDEO_DECODER",O))(ws||{}),ac=(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))(ac||{}),il=(s=>(s[s.MANUAL=0]="MANUAL",s[s.AUTO_AUDIO=1]="AUTO_AUDIO",s[s.AUTO_VIDEO=2]="AUTO_VIDEO",s[s.AUTO_ALL=3]="AUTO_ALL",s))(il||{}),rn=(e=>(e.user="user",e.environment="environment",e))(rn||{}),cc=(s=>(s.BANNED="banned",s.KICK="kick",s.USER_TIME_OUT="user_time_out",s.ROOM_DISBAND="room_disband",s))(cc||{}),rl=(c=>(c[c.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",c[c.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",c[c.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",c[c.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",c[c.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",c[c.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",c[c.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",c[c.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",c[c.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",c))(rl||{}),at=1e8,ic=class{constructor(){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)}},wr=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(wr||{}),Ui=(e=>(e.H264="h264",e.VP8="vp8",e))(Ui||{}),sn=(t=>(t[t.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",t[t.SEI=1]="SEI",t[t.DUMP=2]="DUMP",t))(sn||{}),on=(t=>(t[t.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",t[t.NTP_AUDIO_FRAME=1]="NTP_AUDIO_FRAME",t[t.DUMP=2]="DUMP",t))(on||{});var x={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Ne={AVOID_REPEATED_CALL(r){return`previous ${r.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${Se(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${Se(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:r,rule:i,fnName:e,value:t}){return`the min value of ${r||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:r,rule:i,fnName:e,value:t}){return`the max value of ${r||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(r){return`${r.commandDesc||r.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(r){return`SignalChannel setup failure: (errorCode: ${r.errorCode}, errorMsg: ${r.errorMsg} }).`},ERROR_MESSAGE(r){let i=`${r.type} failed`;return r.message&&(i=`${i}: ${r.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(r){return`exchange sdp failed ${r.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(r){return`'${r}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(r){return`'${r}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:r,code:i}){return`Failed to join room - ${r} code: ${i}`},REJOIN_ROOM_FAILED(r){return`reJoin room: ${r.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:`no permission to publish() under live/${"audience"}, please call switchRole("${"anchor"}") firstly before publish().`,INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(r){return`duplicate ${r} stream publishing, please unpublish your prev ${r} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:r,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${r}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:`role could only be set to a value as ${"anchor"} or ${"audience"}.`,INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(r){return`switchRole failed, errCode: ${r.code} errMsg: ${r.message}.`},CLIENT_BANNED(r){return`client was banned because of ${r.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(r){return`startPublishCDNStream failed, errMsg: ${r.message}.`},STOP_PUBLISH_CDN_FAILED(r){return`stopPublishCDNStream failed, errMsg: ${r.message}.`},INVALID_STREAM_ID(r){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(r){return`cannot replace ${r.kind} track because stream has not ${r.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(r){return`startMixTranscode failed, errMsg: ${r.message}.`},STOP_MIX_TRANSCODE_FAILED(r){return`stopMixTranscode failed, errMsg: ${r.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(r){return`'${r}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:r,fnName:i})=>`'${r}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:r,fnName:i,type:e})=>`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:r=>`${r.media} play failed\uFF0Cbrowser exception: ${r.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(r){return`${r}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(r){return`${r.signalResponse} failed, response code is ${r.code} , errMsg: ${r.message}.`},CATCH_HANDLER_ERROR({name:r,event:i}){return`an error was caught in ${r}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:r}){return`experimental api ${r} does not exist.`},REPEAT_JOIN:r=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:r}){return`failed to call ${r}() because client was destroyed.`},SEI_NOT_SUPPORT:r=>`not support to sendSEIMessage${r===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:r,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${r?"size":"times"} is over ${r?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(r){return`connection aborted due to: ${r}`},API_CALL_ABORTED(r){let i;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${r.userId} ${r.streamType} stream aborted, reason: remote user ${r.userId} unpublished stream.`:i=`API aborted, reason: ${r.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:r=>`'streamType' is required when 'userId' is not '*', calling ${r}()`};var jr={};vr(jr,{ANDROID_VERSION:()=>hc,CHROME_MAJOR_VERSION:()=>yt,CHROME_VERSION:()=>An,EDGE_VERSION:()=>an,EDG_MAJOR_VERSION:()=>pc,EDG_VERSION:()=>cn,FIREFOX_MAJOR_VERSION:()=>mc,FIREFOX_VERSION:()=>nn,HUAWEI_VERSION:()=>En,IE_VERSION:()=>Np,IOS_MAIN_VERSION:()=>di,IOS_VERSION:()=>Bi,IPADQQB_VERSION:()=>_n,IS_ANDROID:()=>fe,IS_ANDROID_WEBVIEW:()=>Ec,IS_ANY_SAFARI:()=>Jr,IS_CHROME:()=>Wr,IS_CHROME_OS:()=>fc,IS_CHROMIUM_BASE:()=>Ct,IS_EDG:()=>Vr,IS_EDGE:()=>Ur,IS_ELECTRON:()=>Dp,IS_FIREFOX:()=>se,IS_HEADLESS_CHROME:()=>gc,IS_HUAWEI:()=>Op,IS_HUAWEIBROWSER:()=>Js,IS_IE:()=>al,IS_IE8:()=>bp,IS_IOS:()=>Je,IS_IOS_13_OR_14:()=>Sc,IS_IOS_15_1:()=>Tc,IS_IPAD:()=>xs,IS_IPADQQB:()=>Hs,IS_IPAD_PRO:()=>lc,IS_IPHONE:()=>or,IS_IPOD:()=>nl,IS_LINUX:()=>Gs,IS_LOCAL:()=>ui,IS_MAC:()=>Rt,IS_MACQQB:()=>$s,IS_MIBROWSER:()=>Ws,IS_MQQB:()=>$r,IS_NATIVE_ANDROID:()=>yp,IS_OLD_ANDROID:()=>Cp,IS_OPPOBROWSER:()=>Hr,IS_SAFARI:()=>je,IS_SAFARI_15_1:()=>Mp,IS_SAMSUNGBROWSER:()=>js,IS_SOGOU:()=>Vs,IS_SOGOUM:()=>Us,IS_TBS:()=>It,IS_UCBROWSER:()=>_c,IS_VIVOBROWSER:()=>Gr,IS_WECHAT:()=>Br,IS_WIN:()=>At,IS_WQQB:()=>Fs,IS_WX:()=>vp,IS_X5MQQB:()=>Fr,IS_XWEB:()=>Bs,MACQQB_VERSION:()=>fn,MI_VERSION:()=>gn,MQQB_VERSION:()=>xr,OPPO_VERSION:()=>Sn,SAFARI_VERSION:()=>Vi,SAMSUNG_VERSION:()=>Tn,SOGOUM_VERSION:()=>dn,SOGOU_VERSION:()=>un,TBS_VERSION:()=>ln,UA_DATA_STRING:()=>Tt,USER_AGENT:()=>St,VIVO_VERSION:()=>In,WECHAT_VERSION:()=>mn,WQQB_VERSION:()=>pn,XWEB_VERSION:()=>hn,browserInfo:()=>Ut,getBrowserInfo:()=>cl,getChromeMajorVersion:()=>ci,getDeviceModel:()=>nr,getOSName:()=>Rn,getOSNumber:()=>Xs,getOSString:()=>hi,getOSType:()=>kp,getTerminalType:()=>Ic,getUserAgentData:()=>qs,isLocalStorageEnabled:()=>li});var St=typeof navigator=="undefined"?"":navigator.userAgent,X=r=>new RegExp(r,"i").test(St),Ie=r=>{if(X(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=St.match(i);if(e&&e[1])return e[1]}return""},uc=r=>{if(X(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=St.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},sl=/AppleWebKit\/([\d.]+)/i.exec(St),Rp=sl?parseFloat(sl[1]):NaN,xs=X("iPad"),lc=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),or=X("iPhone")&&!xs,nl=X("iPod"),Je=or||xs||nl||lc,fe=X("Android"),hc=function(){if(fe){let r=St.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(r){let i=r[1]&&parseFloat(r[1]),e=r[2]&&parseFloat(r[2]);if(i&&e)return parseFloat(`${r[1]}.${r[2]}`);if(i)return i}}return NaN}(),Cp=fe&&X("webkit")&&hc<2.3,yp=fe&&hc<5&&Rp<537,se=X("Firefox"),nn=Ie("Firefox"),mc=uc("Firefox"),Ur=X("Edge"),an=Ie("Edge"),Vr=X("Edg"),cn=Ie("Edg"),pc=uc("Edg"),Us=X("SogouMobileBrowser"),dn=Ie("SogouMobileBrowser"),Vs=X("MetaSr\\s"),un=Ie("MetaSr\\s"),It=X("TBS"),ln=Ie("TBS"),Bs=X("XWEB"),hn=Ie("XWEB"),bp=X("MSIE\\s8\\.0"),al=X("MSIE\\/\\d+"),Np=function(){if(al){let r=/MSIE\s(\d+)\.\d/.exec(St),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(St)&&/rv:11.0/.test(St)&&(i=11),i}return NaN}(),Br=X("(micromessenger|webbrowser)"),mn=Ie("MicroMessenger"),Fr=!It&&X("MQQBrowser")&&X("COVC"),$r=!It&&X("MQQBrowser")&&!X("COVC"),xr=$r||Fr?Ie("MQQBrowser"):"",Fs=!It&&X(" QQBrowser"),pn=Ie(" QQBrowser"),$s=!It&&X("QQBrowserLite"),fn=Ie("QQBrowserLite"),Hs=!It&&X("MQBHD"),_n=Ie("MQBHD"),At=X("Windows"),Rt=!Je&&X("MAC OS X"),Gs=!fe&&X("Linux"),fc=X("CrOS"),vp=X("MicroMessenger"),_c=X("UCBrowser"),Dp=X("Electron"),Ws=X("MiuiBrowser"),gn=Ie("MiuiBrowser"),Js=X("HuaweiBrowser"),Op=X("Huawei"),En=Ie("HuaweiBrowser"),js=X("SamsungBrowser"),Tn=Ie("SamsungBrowser"),Hr=X("HeyTapBrowser"),Sn=Ie("HeyTapBrowser"),Gr=X("VivoBrowser"),In=Ie("VivoBrowser"),ci=()=>uc("Chrome"),Ct=X("Chrome"),Wr=!Ur&&!Vs&&!Us&&!It&&!Bs&&!Vr&&!Fs&&!Ws&&!Js&&!js&&!Hr&&!Gr&&Ct,gc=X("HeadlessChrome"),yt=ci(),An=Ie("Chrome"),je=!Ct&&!$r&&!Fr&&!$s&&!Hs&&X("Safari"),Jr=je||Je,Vi=Ie("Version"),Ec=/Android.*(wv|.0.0.0)/.test(St),Bi=(()=>{if(lc)return Vi;if(Je){let r=St.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),di=Number(Bi.split(".")[0]),Mp=Vi==="15.1",Tc=Bi==="15.1",Sc=(()=>{let r=Number(Bi.split(".")[0]);return r===14||r===13})(),ui=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",li=(()=>{let r;return()=>{if(typeof r=="undefined")try{r=!!window.localStorage}catch(i){r=!1}return r}})(),Ut=cl();function cl(){let r=new Map([[se,["Firefox",nn]],[Vr,["Edg",cn]],[Wr,["Chrome",An]],[je,["Safari",Vi]],[It,["TBS",ln]],[Bs,["XWEB",hn]],[Br&&or,["WeChat",mn]],[Fs,["QQ(Win)",pn]],[$r,["QQ(Mobile)",xr]],[Fr,["QQ(Mobile X5)",xr]],[$s,["QQ(Mac)",fn]],[Hs,["QQ(iPad)",_n]],[Ws,["MI",gn]],[Js,["HW",En]],[js,["Samsung",Tn]],[Hr,["OPPO",Sn]],[Gr,["VIVO",In]],[Ur,["EDGE",an]],[Us,["SogouMobile",dn]],[Vs,["Sogou",un]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var re=null,Tt="";function qs(){return f(this,null,function*(){if(re)return re;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return re=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),re&&!Tt&&(Tt=`UAData: ${re.platform}/${re.platformVersion}`,re.architecture&&re.bitness&&(Tt+=` ${re.architecture}/${re.bitness}`),re.mobile&&(Tt+=" mobile"),re.model&&(Tt+=` model: ${re.model}`),re.fullVersionList&&(Tt+=` ${re.fullVersionList.filter(r=>r.brand!=="Not/A)Brand").map(r=>`${r.brand}/${r.version}`).join(",")}`)),re}catch(r){return null}})}function nr(){return(re==null?void 0:re.model)||""}var ol=new Map([[fe,"Android"],[Je,"iOS"],[At,"Windows"],[Rt,"MacOS"],[Gs,"Linux"],[fc,"ChromeOS"]]),Rn=function(){return ol.get(!0)?ol.get(!0):re?re.platform:"unknown"};function Xs(){return At?1:fe?2:Rt?3:Je?4:Gs?5:fc?6:0}var hi=()=>{let r=Rn();return r+=`/${Ut.name}/${je?Ut.version:Ut.version.split(".")[0]}`,re!=null&&re.platformVersion&&(r+=`/${re.platformVersion}`),re!=null&&re.architecture&&(r+=`/${re.architecture}`),r};function Ic(){return fe?4:or?2:xs?3:Rt?12:At?5:Gs?13:1}function kp(){return fe?"Android":or?"iPhone":xs?"iPad":Rt?"Mac":At?"Windows":Gs?"Linux":"unknown"}var dl=(r,i)=>i?`${wt}/${r}/${i}`:`${wt}/${r}/index.html`;var Pp=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let r=localStorage==null?void 0:localStorage.getItem(Wa);if(r){r=JSON.parse(r);let i=document.createElement("script");i.type="text/javascript",i.text=r.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function U(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,o="",n="",a="";ie(Ne[i])?o=Ne[i](e):K(Ne[i])&&(o=Ne[i]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:c}=Pp();t?a=`${t.className}.html#${t.fnName}`:c&&c[i]&&(ie(c[i])?a=c[i](e):K(c[i])&&(a=c[i]));let l=o;return Vt()&&(d&&d[i]&&(ie(d[i])?n=d[i](e):K(d[i])&&(n=d[i])),n&&(s?l=`${n}
|
|
6
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${
|
|
5
|
+
`}});var Iu=ii(bi=>{var Cr=Kh(),F_=em();bi.write=F_;bi.parse=Cr.parse;bi.parseParams=Cr.parseParams;bi.parseFmtpConfig=Cr.parseFmtpConfig;bi.parsePayloads=Cr.parsePayloads;bi.parseRemoteCandidates=Cr.parseRemoteCandidates;bi.parseImageAttributes=Cr.parseImageAttributes;bi.parseSimulcastStreamList=Cr.parseSimulcastStreamList});import FU from"webrtc-adapter";var $h=ye(xe());var Gu=(k=>(k[k.INVALID_PARAMETER=4096]="INVALID_PARAMETER",k[k.INVALID_OPERATION=4097]="INVALID_OPERATION",k[k.NOT_SUPPORTED=4098]="NOT_SUPPORTED",k[k.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",k[k.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",k[k.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",k[k.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",k[k.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",k[k.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",k[k.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",k[k.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",k[k.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",k[k.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",k[k.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",k[k.CLIENT_BANNED=16448]="CLIENT_BANNED",k[k.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",k[k.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",k[k.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",k[k.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",k[k.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",k[k.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",k[k.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",k[k.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",k[k.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",k[k.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",k[k.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",k[k.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",k[k.API_CALL_ABORTED=16461]="API_CALL_ABORTED",k[k.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",k[k.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",k[k.UNKNOWN=65535]="UNKNOWN",k))(Gu||{}),S=Gu;var Qm=function(s){for(let i in S)if(S[i]===s)return i;return"UNKNOWN"},Ba=class extends Error{constructor({name:e="RtcError",message:t,code:r=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${Qm(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=Ba;var $a=0,Wu=!0,Ju=function(s){$a=s;let i=new Date;i.setTime(i.getTime()+s),y[Wu?"info":"debug"](`baseTime from server: ${i} offset: ${s}`),Wu=!1},ju=function(){return $a},ot=function(){return Date.now()+$a},qo=function(){let s=new Date;return s.setTime(ot()),s.toLocaleString()};var Fe={};vr(Fe,{bytes2ms:()=>Gp,concatArrayBuffers:()=>Pc,convertObjectNumberToInt:()=>Nn,copyProperties:()=>Hp,deepClone:()=>Xr,deepMerge:()=>pi,delay:()=>Fi,fibonacci:()=>qr,formatedTime:()=>Kp,getAbilityConfigUrl:()=>El,getConstructorName:()=>yn,getContainerFromElement:()=>zp,getEnv:()=>Fp,getFirst16Bits:()=>Zp,getInternalVersion:()=>qp,getLast16Bits:()=>ro,getLoggerUrl:()=>Vi,getMuteStateFromFlag:()=>$i,getNetworkType:()=>Sl,getNumNetworkType:()=>Qr,getReconnectionTimeout:()=>Ft,getStringByteLength:()=>bn,getTurnServer:()=>Qp,getUint32Version:()=>Mc,getValueType:()=>Ae,getViewListFromView:()=>to,glog:()=>Rl,ipv4ToUint32:()=>eo,isArray:()=>_e,isAudioWorkletSupported:()=>jp,isBoolean:()=>le,isConstructor:()=>Zs,isEmpty:()=>vc,isFunction:()=>ie,isLangChinese:()=>Ut,isMediaStreamTrack:()=>Jp,isNumber:()=>ee,isObject:()=>yt,isOverseaSdkAppId:()=>zs,isPlainObject:()=>Ze,isPortrait:()=>Oc,isPromise:()=>or,isRemoteTrack:()=>Nt,isString:()=>Y,isUndefined:()=>g,loadImage:()=>io,ms2bytes:()=>Wp,ms2samples:()=>Cl,performanceNow:()=>P,promiseAny:()=>Ys,samples2ms:()=>Al,setNetworkType:()=>Nc,stringify:()=>bt,stringifyIncludeValue:()=>Dc,throttlePromise:()=>kc});var ec={};vr(ec,{AUDIO_MUTE_BIT:()=>Zo,AUDIO_STAT_BIT:()=>Di,AUX_STAT_BIT:()=>Ki,AUX_STREAM_MSID:()=>ja,BACKEND_ENV:()=>Ko,BASE_DOC_URL:()=>Lt,BASE_HOST:()=>qu,CAPABILITIES_KEYS:()=>rn,CLASS_NAME:()=>Ep,CLOUD_CONSOLE_URL:()=>Zm,CROSS_ROOM_BIT:()=>Ja,DATA_FREEZE_TIMING:()=>tn,DOC_URL:()=>ep,DTLS_STATE_UNKNOWN:()=>ft,ENV_NAME:()=>ri,EXCHANGE_SDP_TIMEOUT:()=>Ya,INTERVAL:()=>tr,IS_WORKER:()=>Dr,IS_WORKLET:()=>Ns,KIBANA_EVENT:()=>Ge,LOCAL_STREAM_PUBLISH_STATE:()=>zu,LOGGER_CMD_TYPE:()=>Ni,LOGGER_DOMAIN:()=>Ha,LOGGER_DOMAIN_OVERSEA:()=>Ga,LOG_LEVEL:()=>pt,LOG_LEVEL_NAME:()=>Tp,MAIN_STREAM_MSID:()=>Os,MAX_RTT:()=>Ls,MICROPHONE_COMMUNICATIONS:()=>gp,MICROPHONE_DEFAULT:()=>er,MUTE_ALL_BIT:()=>rp,NAME:()=>h,NETWORK_TYPE:()=>Xo,NOT_SUPPORTED_H264:()=>Zi,PAUSED_RETRY_COUNT:()=>Ka,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Ms,PEER_CONNECTION_STATE:()=>ne,PEER_LEAVE_REASON:()=>Za,RAF:()=>Ps,RECOVER_CAPTURE_INTERVAL:()=>kr,REMOTE_STREAM_TYPE_AUX:()=>Xa,REMOTE_STREAM_TYPE_MAIN:()=>qa,RENDER_FREEZE_TIMING:()=>mp,RIC:()=>Mi,SCHEDULE_DOMAIN:()=>_t,SCHEDULE_TIMEOUT:()=>_p,SDP_SEMANTICS_PLAN_B:()=>Or,SDP_SEMANTICS_UNIFIED_PLAN:()=>Oi,SECOND_HOST:()=>Ym,SIGNAL_PING_PONG_INTERVAL:()=>ip,SIGNAL_PING_TIMEOUT:()=>tp,SIGNAL_RECONNECTION_COUNT:()=>lp,SMALL_STAT_BIT:()=>Ds,SPEAKER_DEFAULT:()=>ks,STORAGE_EXPIRES_TIME:()=>Qo,STREAM_TYPE_BIG:()=>pp,STREAM_TYPE_SMALL:()=>fp,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Mr,SYNC_USER_LIST_INTERVAL:()=>hp,Scene:()=>xt,Switch:()=>Xu,THIRD_HOST:()=>Km,TIMEOUT:()=>ki,TRANSPORT_DIRECTION:()=>z,TRTC_ERROR_ASSISTANCE:()=>Wa,TRTC_QUALITY_BAD:()=>cp,TRTC_QUALITY_DISCONNECTED:()=>up,TRTC_QUALITY_EXCELLENT:()=>op,TRTC_QUALITY_GOOD:()=>np,TRTC_QUALITY_POOR:()=>ap,TRTC_QUALITY_UNKNOWN:()=>sp,TRTC_QUALITY_VERY_BAD:()=>dp,UPDATE_OFFER_TIMEOUT:()=>za,VIDEO_MUTE_BIT:()=>en,VIDEO_STAT_BIT:()=>vi,audioProfileMap:()=>zo,getRetryCount:()=>si,getScriptDir:()=>zm,innerVersion:()=>bs,loggerProxy:()=>vs,screenProfileMap:()=>Yo,setLoggerProxy:()=>Yi,setRetryCount:()=>Qa,setVersion:()=>Fa,version:()=>Ie,videoProfileMap:()=>nt});var bs="4.15.00.1600",Ie="5.0.0";function Fa(s){Ie=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));bs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Dr=typeof importScripts!="undefined",Ns=typeof registerProcessor!="undefined",zm=()=>{let s=Dr?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},vs="",Yi=s=>vs=s,qu="web.sdk.qcloud.com",Ym="web.sdk.tencent.cn",Km="web.sdk.cloud.tencent.cn",Zm="https://console.cloud.tencent.com/trtc",Lt=`https://${qu}/trtc/webrtc/v5/doc`,ep=`${Lt}/zh-cn/`,Ha="https://yun.tim.qq.com",Ga="https://apisgp.my-imcloud.com",Wa="trtc_error_assistance",Ni={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ri={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},pt=(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))(pt||{}),tp=18e3,ip=2e3,Xo={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Qo=7*24*3600*1e3,Xu=(r=>(r.USEAINS="useAINS",r.ENABLEDEBUG="enableDebug",r.USEV2="useV2",r.USEWT="useWt",r))(Xu||{}),zo={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}},nt={"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}},Yo={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},h={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},z={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Ko={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},xt=(e=>(e.LIVE="live",e.RTC="rtc",e))(xt||{}),vi=1,Ds=2,Ki=4,Di=8,Zo=64,en=16,rp=112,Ja=128,Os="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ja="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",qa=h.MAIN,Xa=h.AUXILIARY,sp=0,op=1,np=2,ap=3,cp=4,dp=5,up=6,ft="unknown",ne={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Qu=1/0;function Qa(s){Qu=s}function si(){return Qu}var lp=30,Ge={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"},hp=1e4,za=1e4,Ya=1e4,Oi="unified-plan",Or="plan-b",Zi=1028,zu=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(zu||{}),tn=500,mp=1e3,pp=h.BIG,fp=h.SMALL,Ms=10*1e3,_t={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},_p=2e3,Ep={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Ka=5,er="default",ks=er,gp="communications",Tp=Object.keys(pt),Za=["normal leave","timeout leave","kick","role change"],Mr=10,kr=2e3,Mi="ric",Ps="raf",tr="interval",ki="timeout",rn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Ls=10*1e3;function oi({url:s,body:i,method:e,timeout:t}){let r=new XMLHttpRequest;return new Promise((o,n)=>{r.onreadystatechange=()=>{if(r.readyState===4)if(r.status>=200&&r.status<300)try{let a=JSON.parse(r.response);o({data:a})}catch(a){o({data:r.response})}else n({status:r.status,statusText:r.statusText||"request failed!"})},r.timeout=t||5e3,r.open(e||"POST",s,!0),r.send(i)})}function tc(s){return f(this,null,function*(){let i=P(),e=JSON.stringify(s);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return y.debug(`compressJSON ${e.length} -> ${a.byteLength} ${P()-i}ms`),a}catch(t){return e}})}var uc={};vr(uc,{AUDIO_LEVEL_SCALE:()=>at,AudioCodecPipelineType:()=>dc,AudioType:()=>el,BASIC_TYPE:()=>Lr,BannedReason:()=>cc,CONNECTION_CLOSED_REASON:()=>rc,ClientEvent:()=>Yu,ConnectionEvent:()=>Et,ConnectionState:()=>Ye,FacingMode:()=>on,LeaveReason:()=>sl,LocalTrackEvent:()=>xs,MULTI_VIDEO_DATA_TYPE:()=>gt,MediaType:()=>be,MediaTypeLabel:()=>Sp,MonitorEventId:()=>ws,MutedFlag:()=>Zu,NetworkQualityValue:()=>ac,PlayerState:()=>Pr,ReceiveMode:()=>rl,RemoteStreamType:()=>Ke,RemoteTrackEvent:()=>sn,RoomEvent:()=>Pi,SceneNumber:()=>sc,StreamEvent:()=>Ku,StreamType:()=>il,SubscribeMediaType:()=>ic,TRACK_ACTION:()=>nc,TRACK_KIND:()=>oc,TrackEvent:()=>Li,UserRole:()=>we,UserRoleNumber:()=>ir,VideoCodec:()=>xi,VideoCodecPipelineType:()=>nn,VideoType:()=>tl});var Et=(A=>(A.TRACK_ADDED="track-added",A.TRACK_UPDATED="track-updated",A.TRACK_SUBSCRIBED="track-subscribed",A.STREAM_ADDED="stream-added",A.STREAM_REMOVED="stream-removed",A.STREAM_UPDATED="stream-updated",A.STREAM_PUBLISHED="stream-published",A.STREAM_SUBSCRIBED="stream-subscribed",A.STREAM_UNSUBSCRIBED="stream-unsubscribed",A.STATE_CHANGED="state-changed",A.ERROR="error",A.CONNECTION_STATE_CHANGED="connection-state-changed",A.FIREWALL_RESTRICTION="firewall-restriction",A.SEI_MESSAGE="sei-message",A.CLOSED="closed",A))(Et||{}),rc=(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))(rc||{}),Yu=(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))(Yu||{}),Ku=(o=>(o.PLAYER_STATE_CHANGED="player-state-changed",o.SCREEN_SHARING_STOPPED="screen-sharing-stopped",o.CONNECTION_STATE_CHANGED="connection-state-changed",o.DEVICE_AUTO_RECOVERED="device-auto-recovered",o.ERROR="error",o))(Ku||{}),xs=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(xs||{}),sn=(e=>(e.FLAG_CHANGED="flag-changed",e.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",e))(sn||{}),Pr=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Pr||{}),Pi=(C=>(C.PEER_JOIN="peer-join",C.PEER_LEAVE="peer-leave",C.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",C.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",C.BANNED="banned",C.NETWORK_QUALITY="network-quality",C.AUDIO_VOLUME="audio-volume",C.SEI_MESSAGE="sei-message",C.ERROR="error",C.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",C.REMOTE_PUBLISHED="remote-published",C.REMOTE_UNPUBLISHED="remote-unpublished",C.FIREWALL_RESTRICTION="firewall-restriction",C.HEARTBEAT_REPORT="heartbeat-report",C.CUSTOM_MESSAGE="custom-message",C.NTP_TIME_UPDATED="ntp-time-updated",C))(Pi||{}),Li=(n=>(n.PLAYER_STATE_CHANGED="player-state-changed",n.MUTE="mute",n.UNMUTE="unmute",n.ERROR="error",n.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",n.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",n))(Li||{}),Zu=(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))(Zu||{}),sc=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(sc||{}),ir=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(ir||{}),we=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(we||{}),Ye=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(Ye||{}),oc=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(oc||{}),nc=(e=>(e.ADD="add",e.REMOVE="remove",e))(nc||{}),be=(o=>(o[o.NULL=0]="NULL",o[o.AUDIO=1]="AUDIO",o[o.AUX_VIDEO=2]="AUX_VIDEO",o[o.BIG_VIDEO=4]="BIG_VIDEO",o[o.SMALL_VIDEO=8]="SMALL_VIDEO",o))(be||{}),Sp={[1]:"audio",[2]:"auxVideo",[4]:"video"},el=(i=>(i[i.opus=111]="opus",i))(el||{}),tl=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(tl||{}),il=(e=>(e.Big="big",e.Small="small",e))(il||{}),Ke=(e=>(e.Main="main",e.Aux="auxiliary",e))(Ke||{}),gt=(o=>(o[o.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",o[o.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",o[o.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",o[o.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",o[o.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",o))(gt||{}),ws=(O=>(O[O.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",O[O.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",O[O.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",O[O.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",O[O.MUTE_AUDIO=32772]="MUTE_AUDIO",O[O.MUTE_VIDEO=32773]="MUTE_VIDEO",O[O.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",O[O.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",O[O.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",O[O.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",O[O.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",O[O.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",O[O.SWITCH_CAMERA=32780]="SWITCH_CAMERA",O[O.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",O[O.REPLACE_VIDEO=32782]="REPLACE_VIDEO",O[O.REPLACE_AUDIO=32783]="REPLACE_AUDIO",O[O.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",O[O.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",O[O.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",O[O.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",O[O.JOIN=32788]="JOIN",O[O.LEAVE=32789]="LEAVE",O[O.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",O[O.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",O[O.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",O[O.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",O[O.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",O[O.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",O[O.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",O[O.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",O[O.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",O[O.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",O[O.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",O[O.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",O[O.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",O[O.PUBLISH_AUX=32805]="PUBLISH_AUX",O[O.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",O[O.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",O[O.VIDEO_ENCODER=4004]="VIDEO_ENCODER",O[O.VIDEO_DECODER=4005]="VIDEO_DECODER",O))(ws||{}),ac=(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))(ac||{}),rl=(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))(rl||{}),on=(e=>(e.user="user",e.environment="environment",e))(on||{}),cc=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(cc||{}),sl=(d=>(d[d.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",d[d.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",d[d.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",d[d.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",d[d.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",d[d.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",d[d.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",d[d.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",d[d.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",d))(sl||{}),at=1e8,ic=class{constructor(){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)}},Lr=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Lr||{}),xi=(e=>(e.H264="h264",e.VP8="vp8",e))(xi||{}),nn=(t=>(t[t.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",t[t.SEI=1]="SEI",t[t.DUMP=2]="DUMP",t))(nn||{}),dc=(t=>(t[t.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",t[t.NTP_AUDIO_FRAME=1]="NTP_AUDIO_FRAME",t[t.DUMP=2]="DUMP",t))(dc||{});var w={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"},Ne={AVOID_REPEATED_CALL(s){return`previous ${s.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:s,rule:i,fnName:e,value:t}){return`the min value of ${s||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:s,rule:i,fnName:e,value:t}){return`the max value of ${s||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(s){return`${s.commandDesc||s.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(s){return`SignalChannel setup failure: (errorCode: ${s.errorCode}, errorMsg: ${s.errorMsg} }).`},ERROR_MESSAGE(s){let i=`${s.type} failed`;return s.message&&(i=`${i}: ${s.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(s){return`exchange sdp failed ${s.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(s){return`'${s}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(s){return`'${s}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:s,code:i}){return`Failed to join room - ${s} code: ${i}`},REJOIN_ROOM_FAILED(s){return`reJoin room: ${s.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:`no permission to publish() under live/${"audience"}, please call switchRole("${"anchor"}") firstly before publish().`,INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(s){return`duplicate ${s} stream publishing, please unpublish your prev ${s} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:s,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${s}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:`role could only be set to a value as ${"anchor"} or ${"audience"}.`,INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(s){return`switchRole failed, errCode: ${s.code} errMsg: ${s.message}.`},CLIENT_BANNED(s){return`client was banned because of ${s.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(s){return`startPublishCDNStream failed, errMsg: ${s.message}.`},STOP_PUBLISH_CDN_FAILED(s){return`stopPublishCDNStream failed, errMsg: ${s.message}.`},INVALID_STREAM_ID(s){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(s){return`cannot replace ${s.kind} track because stream has not ${s.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(s){return`startMixTranscode failed, errMsg: ${s.message}.`},STOP_MIX_TRANSCODE_FAILED(s){return`stopMixTranscode failed, errMsg: ${s.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(s){return`'${s}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:s,fnName:i})=>`'${s}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:s,fnName:i,type:e})=>`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:s=>`${s.media} play failed\uFF0Cbrowser exception: ${s.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(s){return`${s}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(s){return`${s.signalResponse} failed, response code is ${s.code} , errMsg: ${s.message}.`},CATCH_HANDLER_ERROR({name:s,event:i}){return`an error was caught in ${s}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:s}){return`experimental api ${s} does not exist.`},REPEAT_JOIN:s=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:s}){return`failed to call ${s}() because client was destroyed.`},SEI_NOT_SUPPORT:s=>`not support to sendSEIMessage${s===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:s,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${s?"size":"times"} is over ${s?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(s){return`connection aborted due to: ${s}`},API_CALL_ABORTED(s){let i;return s.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${s.userId} ${s.streamType} stream aborted, reason: remote user ${s.userId} unpublished stream.`:i=`API aborted, reason: ${s.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:s=>`'streamType' is required when 'userId' is not '*', calling ${s}()`};var Jr={};vr(Jr,{ANDROID_VERSION:()=>mc,CHROME_MAJOR_VERSION:()=>Rt,CHROME_VERSION:()=>Cn,EDGE_VERSION:()=>cn,EDG_MAJOR_VERSION:()=>fc,EDG_VERSION:()=>dn,FIREFOX_MAJOR_VERSION:()=>pc,FIREFOX_VERSION:()=>an,HUAWEI_VERSION:()=>Tn,IE_VERSION:()=>yp,IOS_MAIN_VERSION:()=>ci,IOS_VERSION:()=>Ui,IPADQQB_VERSION:()=>En,IS_ANDROID:()=>fe,IS_ANDROID_WEBVIEW:()=>Tc,IS_ANY_SAFARI:()=>Wr,IS_CHROME:()=>Gr,IS_CHROME_OS:()=>_c,IS_CHROMIUM_BASE:()=>Ct,IS_EDG:()=>Ur,IS_EDGE:()=>wr,IS_ELECTRON:()=>Np,IS_FIREFOX:()=>se,IS_HEADLESS_CHROME:()=>gc,IS_HUAWEI:()=>vp,IS_HUAWEIBROWSER:()=>js,IS_IE:()=>cl,IS_IE8:()=>Rp,IS_IOS:()=>We,IS_IOS_13_OR_14:()=>Ic,IS_IOS_15_1:()=>Sc,IS_IPAD:()=>Us,IS_IPADQQB:()=>Gs,IS_IPAD_PRO:()=>hc,IS_IPHONE:()=>rr,IS_IPOD:()=>al,IS_LINUX:()=>Ws,IS_LOCAL:()=>di,IS_MAC:()=>At,IS_MACQQB:()=>Hs,IS_MIBROWSER:()=>Js,IS_MQQB:()=>$r,IS_NATIVE_ANDROID:()=>Cp,IS_OLD_ANDROID:()=>Ap,IS_OPPOBROWSER:()=>Fr,IS_SAFARI:()=>Je,IS_SAFARI_15_1:()=>Dp,IS_SAMSUNGBROWSER:()=>qs,IS_SOGOU:()=>Bs,IS_SOGOUM:()=>Vs,IS_TBS:()=>It,IS_UCBROWSER:()=>Ec,IS_VIVOBROWSER:()=>Hr,IS_WECHAT:()=>Vr,IS_WIN:()=>ni,IS_WQQB:()=>Fs,IS_WX:()=>bp,IS_X5MQQB:()=>Br,IS_XWEB:()=>$s,MACQQB_VERSION:()=>_n,MI_VERSION:()=>gn,MQQB_VERSION:()=>xr,OPPO_VERSION:()=>In,SAFARI_VERSION:()=>wi,SAMSUNG_VERSION:()=>Sn,SOGOUM_VERSION:()=>un,SOGOU_VERSION:()=>ln,TBS_VERSION:()=>hn,UA_DATA_STRING:()=>Tt,USER_AGENT:()=>St,VIVO_VERSION:()=>An,WECHAT_VERSION:()=>pn,WQQB_VERSION:()=>fn,XWEB_VERSION:()=>mn,browserInfo:()=>wt,getBrowserInfo:()=>dl,getChromeMajorVersion:()=>ai,getDeviceModel:()=>sr,getOSName:()=>Rn,getOSNumber:()=>Qs,getOSString:()=>li,getOSType:()=>Op,getTerminalType:()=>Ac,getUserAgentData:()=>Xs,isLocalStorageEnabled:()=>ui});var St=typeof navigator=="undefined"?"":navigator.userAgent,X=s=>new RegExp(s,"i").test(St),Ce=s=>{if(X(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=St.match(i);if(e&&e[1])return e[1]}return""},lc=s=>{if(X(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=St.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},ol=/AppleWebKit\/([\d.]+)/i.exec(St),Ip=ol?parseFloat(ol[1]):NaN,Us=X("iPad"),hc=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),rr=X("iPhone")&&!Us,al=X("iPod"),We=rr||Us||al||hc,fe=X("Android"),mc=function(){if(fe){let s=St.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(s){let i=s[1]&&parseFloat(s[1]),e=s[2]&&parseFloat(s[2]);if(i&&e)return parseFloat(`${s[1]}.${s[2]}`);if(i)return i}}return NaN}(),Ap=fe&&X("webkit")&&mc<2.3,Cp=fe&&mc<5&&Ip<537,se=X("Firefox"),an=Ce("Firefox"),pc=lc("Firefox"),wr=X("Edge"),cn=Ce("Edge"),Ur=X("Edg"),dn=Ce("Edg"),fc=lc("Edg"),Vs=X("SogouMobileBrowser"),un=Ce("SogouMobileBrowser"),Bs=X("MetaSr\\s"),ln=Ce("MetaSr\\s"),It=X("TBS"),hn=Ce("TBS"),$s=X("XWEB"),mn=Ce("XWEB"),Rp=X("MSIE\\s8\\.0"),cl=X("MSIE\\/\\d+"),yp=function(){if(cl){let s=/MSIE\s(\d+)\.\d/.exec(St),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(St)&&/rv:11.0/.test(St)&&(i=11),i}return NaN}(),Vr=X("(micromessenger|webbrowser)"),pn=Ce("MicroMessenger"),Br=!It&&X("MQQBrowser")&&X("COVC"),$r=!It&&X("MQQBrowser")&&!X("COVC"),xr=$r||Br?Ce("MQQBrowser"):"",Fs=!It&&X(" QQBrowser"),fn=Ce(" QQBrowser"),Hs=!It&&X("QQBrowserLite"),_n=Ce("QQBrowserLite"),Gs=!It&&X("MQBHD"),En=Ce("MQBHD"),ni=X("Windows"),At=!We&&X("MAC OS X"),Ws=!fe&&X("Linux"),_c=X("CrOS"),bp=X("MicroMessenger"),Ec=X("UCBrowser"),Np=X("Electron"),Js=X("MiuiBrowser"),gn=Ce("MiuiBrowser"),js=X("HuaweiBrowser"),vp=X("Huawei"),Tn=Ce("HuaweiBrowser"),qs=X("SamsungBrowser"),Sn=Ce("SamsungBrowser"),Fr=X("HeyTapBrowser"),In=Ce("HeyTapBrowser"),Hr=X("VivoBrowser"),An=Ce("VivoBrowser"),ai=()=>lc("Chrome"),Ct=X("Chrome"),Gr=!wr&&!Bs&&!Vs&&!It&&!$s&&!Ur&&!Fs&&!Js&&!js&&!qs&&!Fr&&!Hr&&Ct,gc=X("HeadlessChrome"),Rt=ai(),Cn=Ce("Chrome"),Je=!Ct&&!$r&&!Br&&!Hs&&!Gs&&X("Safari"),Wr=Je||We,wi=Ce("Version"),Tc=/Android.*(wv|.0.0.0)/.test(St),Ui=(()=>{if(hc)return wi;if(We){let s=St.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})(),ci=Number(Ui.split(".")[0]),Dp=wi==="15.1",Sc=Ui==="15.1",Ic=(()=>{let s=Number(Ui.split(".")[0]);return s===14||s===13})(),di=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",ui=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),wt=dl();function dl(){let s=new Map([[se,["Firefox",an]],[Ur,["Edg",dn]],[Gr,["Chrome",Cn]],[Je,["Safari",wi]],[It,["TBS",hn]],[$s,["XWEB",mn]],[Vr&&rr,["WeChat",pn]],[Fs,["QQ(Win)",fn]],[$r,["QQ(Mobile)",xr]],[Br,["QQ(Mobile X5)",xr]],[Hs,["QQ(Mac)",_n]],[Gs,["QQ(iPad)",En]],[Js,["MI",gn]],[js,["HW",Tn]],[qs,["Samsung",Sn]],[Fr,["OPPO",In]],[Hr,["VIVO",An]],[wr,["EDGE",cn]],[Vs,["SogouMobile",un]],[Bs,["Sogou",ln]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var re=null,Tt="";function Xs(){return f(this,null,function*(){if(re)return re;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return re=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),re&&!Tt&&(Tt=`UAData: ${re.platform}/${re.platformVersion}`,re.architecture&&re.bitness&&(Tt+=` ${re.architecture}/${re.bitness}`),re.mobile&&(Tt+=" mobile"),re.model&&(Tt+=` model: ${re.model}`),re.fullVersionList&&(Tt+=` ${re.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),re}catch(s){return null}})}function sr(){return(re==null?void 0:re.model)||""}var nl=new Map([[fe,"Android"],[We,"iOS"],[ni,"Windows"],[At,"MacOS"],[Ws,"Linux"],[_c,"ChromeOS"]]),Rn=function(){return nl.get(!0)?nl.get(!0):re?re.platform:"unknown"};function Qs(){return ni?1:fe?2:At?3:We?4:Ws?5:_c?6:0}var li=()=>{let s=Rn();return s+=`/${wt.name}/${Je?wt.version:wt.version.split(".")[0]}`,re!=null&&re.platformVersion&&(s+=`/${re.platformVersion}`),re!=null&&re.architecture&&(s+=`/${re.architecture}`),s};function Ac(){return fe?4:rr?2:Us?3:At?12:ni?5:Ws?13:1}function Op(){return fe?"Android":rr?"iPhone":Us?"iPad":At?"Mac":ni?"Windows":Ws?"Linux":"unknown"}var ul=(s,i)=>i?`${Lt}/${s}/${i}`:`${Lt}/${s}/index.html`;var Mp=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let s=localStorage==null?void 0:localStorage.getItem(Wa);if(s){s=JSON.parse(s);let i=document.createElement("script");i.type="text/javascript",i.text=s.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function U(s){let{key:i,data:e,link:t,addDocLink:r=!0}=s,o="",n="",a="";ie(Ne[i])?o=Ne[i](e):Y(Ne[i])&&(o=Ne[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Mp();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(ie(d[i])?a=d[i](e):Y(d[i])&&(a=d[i]));let l=o;return Ut()&&(c&&c[i]&&(ie(c[i])?n=c[i](e):Y(c[i])&&(n=c[i])),n&&(r?l=`${n}
|
|
6
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${ul("zh-cn",a)}
|
|
7
7
|
|
|
8
8
|
`:l=`${n}
|
|
9
9
|
|
|
10
|
-
`,l+=o)),
|
|
11
|
-
Refer to: ${
|
|
12
|
-
`),l}var
|
|
13
|
-
${t.stack}`)),this.sendRequest(
|
|
14
|
-
`));function $t(r){le(r)&&r!==Cc&&(Cc=r,y.info(`setIsNeedToSchedule ${r}`))}T.on("28",()=>$t(!0));T.on("63",()=>$t(!0));T.on("84",()=>$t(!0));T.on("201",r=>{r.state==="RECONNECTING"&&$t(!0)});T.on("202",r=>{r.state==="RECONNECTING"&&$t(!0)});function Fp(r,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let s=performance.getEntriesByType("resource"),o=qr(r,h.MAIN),n=qr(r,h.BACKUP);for(let a of s)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let d=a.name===o?h.MAIN:h.BACKUP,c=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),I=Math.round(a.requestStart-a.secureConnectionStart),A=Math.round(a.secureConnectionStart-a.connectStart),R=Math.round(a.responseStart-a.requestStart),$=Math.round(a.responseEnd-a.responseStart),Me=[_,I,A,R,$];Z.uploadEvent({log:`stat-schedule-net:${c}(${l}(${m}->${p})->${Me.join("->")}) ${d}`,userId:i}),t=w(D({},t),{totalCost:c,local:l,dns:_,tcp:A,tls:I,request:R,response:$});break}}catch(s){y.error("getScheduleDetailCost error",s)}return t}function fl(c){return f(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:o,frameWorkType:n,role:a,latencyLevel:d}){if(!Cc&&Rc)return{isCached:!0,result:Rc};let l={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(r)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",o),m.append("userSig",String(s)),a&&m.append("role",String(a)),d&&m.append("latencyLevel",String(d)),n&&m.append("frameWorkType",String(n));let p=P(),_=yield Hp(m,l,i);_.config&&(_.config.loggerDomain&&Zi(_.config.loggerDomain),le(_.config.scheduleCache)&&$t(!_.config.scheduleCache)),l.delta=P()-p;let I=Fp(Number(i),r,p);return Rc=_,{isCached:!1,result:_,detailCost:I}}catch(m){let p=_e(m)?m[0]:m,_=te(p.code)?p.code:0,I=`schedule failed${p.message?`: ${p.message}`:""}`,A=new b({code:S.SCHEDULE_FAILED,extraCode:_,message:U({key:x.JOIN_ROOM_FAILED,data:{error:I,code:_}})});throw y.error(I,_),A}})}var $i={main:"",backup:""};function yc(r){_e(r)?($i.main=r[0],$i.backup=r[1]):$i.main=r}function qr(r,i=h.MAIN,e=!1){return`https://${$i[i]||gl(r,i,e)}/api/v1/config`}function _l(r,i=h.MAIN){return`https://${$i[i]||gl(r,i)}/api/v1/trtcAutoConf`}function gl(r,i=h.MAIN,e=!1){if(Qs(r))return i===h.MAIN?_t.MAIN_OVERSEA:_t.BACKUP_OVERSEA;let t;return Qs(r)?e?t=i===h.MAIN?_t.MAIN_OVERSEA_OLD:_t.BACKUP_OVERSEA_OLD:t=i===h.MAIN?_t.MAIN_OVERSEA:_t.BACKUP_OVERSEA:t=i===h.MAIN?_t.MAIN:_t.BACKUP,t}function $p(r,i,e){return new Promise((t,s)=>{ai({url:r,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var pl=(r,i)=>Ft({retryFunction:$p,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function Hp(r,i,e){return new Promise((t,s)=>{let o=null;zs([pl(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:c})=>{i.msg[0]=n.message,o||(d>=2&&(c[0]=qr(e,h.MAIN,!0)),a())})(qr(e,h.MAIN),r,{get timeout(){return Xr(2+i.count[0])*1e3}}),pl(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:c})=>{i.msg[1]=n.message,o||(d>=2&&(c[0]=qr(e,h.BACKUP,!0)),a())})(qr(e,h.BACKUP),r,{get timeout(){return Xr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var Gp=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Qs=r=>Number(r)<14e8,Fi=function(r,i){let e;vs?e=vs:e=Qs(r)?Ga:Ha;let t=Math.floor(Math.random()*Cs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},Ys="unknown";function Tl(){if(Ys!=="unknown")return Ys;let{userAgent:r,connection:i}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),s=i&&i.effectiveType&&i.effectiveType.toLowerCase();return s==="slow-2"&&(s="2g"),t&&(Ys=Sl(t,s)),Ys}function Sl(r,i){if(qo[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function bc(r){Ys=Sl(r)}function zr(){return qo[Tl()]}function Wp(r,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(r,e,t)}return r}function Jp(r,i=48e3){return Il(r/4,i)}function Il(r,i=48e3){return r*1e3/i}function jp(r,i=48e3){return Al(r,i)*4}function Al(r,i=48e3){return r*i/1e3}var Rl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Vt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},et=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Xr(r,i=1,e=1){return r<=1?e:Xr(r-1,e,i+e)}function Ht(r){return r>8?30*1e3:Xr(r)*1e3}function Se(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ie=r=>typeof r=="function",E=r=>typeof r=="undefined",K=r=>typeof r=="string",te=r=>typeof r=="number",le=r=>typeof r=="boolean",bt=r=>Se(r)==="object",_e=r=>Se(r)==="array",qp=r=>Se(r)==="MediaStreamTrack".toLowerCase(),vt=r=>r.isRemote,ar=r=>Se(r)==="promise",Ks=r=>ie(r)&&r.prototype.constructor===r,Cn=r=>Ks(r)?r.prototype.constructor.name:"",Xp=typeof AudioWorkletNode!="undefined";function zs(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(o=>{t.push(o),t.length===r.length&&e(t)})})})}function P(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var El=r=>+r<10?`0${r}`:r,Qp=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=El(e[1])+El(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},zp=Object.prototype.hasOwnProperty,{toString:aE}=Object.prototype;function Nc(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(et(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(zp.call(r,i))return!1;return!0}}return!1}function Hi(r,i){return{userId:i,hasAudio:!!(r&Mi),hasVideo:!!(r&Oi),hasAuxiliary:!!(r&er),hasSmall:!!(r&Ds),audioMuted:!!(r&Ko),videoMuted:!!(r&Zo),audioAvailable:!!(r&Mi)&&!(r&Ko),videoAvailable:!!(r&Oi)&&!(r&Zo)}}function Yp(r){let i={urls:r.url.startsWith("turn:")||r.url.startsWith("turns:")?r.url:`turn:${r.url}`};return!E(r.username)&&!E(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",E(r.credentialType)||(i.credentialType=r.credentialType)),i}function Zs(r,i=!0){if(!K(r))return 0;let e=r.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var fi=function(r,i,e,t){if(!(bt(r)&&bt(i)))return 0;let s=0,o=Object.keys(i),n;for(let a=0,d=o.length;a<d;a++)if(n=o[a],!(E(i[n])||e&&e.includes(n)))if(bt(r[n])&&bt(i[n]))s+=fi(r[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;r[n]!==i[n]&&(r[n]=Qr(i[n]),s+=1)}return s};function Qr(r){if(_e(r)){let i=[];return r.forEach((e,t)=>{i[t]=Qr(e)}),i}if(bt(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=Qr(r[e])}),i}return r}var eo=r=>{let i=[];if(_e(r))i=[...r];else if(K(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},Kp=r=>K(r)?document.getElementById(r):r,Zp=r=>{let i=d=>d<10?`0${d}`:`${d}`,e=r.getFullYear(),t=r.getMonth()+1,s=r.getDate(),o=i(r.getHours()),n=i(r.getMinutes()),a=i(r.getSeconds());return`${e}/${t}/${s} ${o}:${n}:${a}`},ef=()=>Zp(new Date);function Nt(r,{keysToInclude:i,keysToExclude:e}){try{if(_e(r))return`[${r.map(n=>Nt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!et(r)||!_e(i)&&!_e(e))return JSON.stringify(r);let t={},s=new Set(i),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(t[n]=et(r[n])||_e(r[n])?JSON.parse(Nt(r[n],{keysToExclude:e,keysToInclude:i})):r[n])}),JSON.stringify(t)}catch(t){return"{}"}}function vc(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),Nt(r,{keysToInclude:e})}function yn(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Dc=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},to=r=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(K(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${r}`}))}})}),Oc=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},bn=r=>(Object.keys(r).forEach(i=>{te(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(et(r[i])||_e(r[i]))&&bn(r[i])}),r);function Gi(r,i){return new Promise(e=>{let t=setTimeout(e,r);i&&i(t)})}var Mc=(r,i)=>{let e=null;return function(...t){return e||(e=r.apply(i||this,t),e.finally(()=>e=null),e)}};function io(r,i){let e=new Uint8Array(r.byteLength+i.byteLength);return e.set(new Uint8Array(r),0),e.set(new Uint8Array(i),r.byteLength),e.buffer}function _i(r){return(r&65535)>>>0}function tf(r){return(r&4294901760)>>>0}var Yr=class{constructor(i){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=ul(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),y.log(i,e,mi(this.userId)||ll(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 g=pi;var rf="%cTRTC%c%s",sf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",of="display: inline",nf=!(Je||fe||gc),kc=class{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!Dr&&!Ns&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(g.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&pt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(g.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(g.JOIN_FAILED,()=>{this.startUpload()}),T.on(g.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:o})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})});else if(K(t.userId)&&te(t.sdkAppId)){let{userId:s,sdkAppId:o}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let s=[...i.values()];for(let o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:d}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:jo(),sdkAppId:String(a),userId:n,version:Te,log:d.map(c=>c.log).join(`
|
|
15
|
-
`)}),a),d.forEach(c=>c.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Ft({retryFunction:()=>ai({url:Fi(e,Di.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime($e());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${pt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(pt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(K(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,o){var d;e.unshift(this.getPrefix(i));let n={log:e.reduce((c,l)=>`${c} ${this.logChunkToString(l)}`.trim(),""),level:i,userId:s,sdkAppId:o,forAllJoinedClients:t};if(T.emit(g.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((d=pt[i])==null?void 0:d.toLowerCase())||"info";nf?console[a](rf,sf,of,...e):console[a](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new Yr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;pt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},y=new kc;var af=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let i=Math.random()*16|0;return(r=="x"?i:i&3|8).toString(16)})},ro=af;var Pc=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!li())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=localStorage.getItem(t);if(!s)return!1;let o=JSON.parse(s);if(o&&o.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!li())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){y.warn(i)}}getItem(i){if(!li())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){y.warn(e)}}setItem(i,e){if(!!li())try{let t={expiresIn:Date.now()+Xo,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){y.warn(t)}}deleteItem(i){if(!li())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return y.warn(e),!1}}clear(){if(!!li())try{localStorage.clear()}catch(i){y.warn(i)}}},Nn=new Pc;var Jt={};vr(Jt,{HTTPS_API:()=>Cf,IS_GET_CAPABILITIES_SUPPORTED:()=>Jc,IS_GET_SETTINGS_SUPPORTED:()=>Wt,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Wc,IS_INSERTABLE_STREAM_SUPPORTED:()=>Dt,IS_RTC_RTP_SENDER_SUPPORTED:()=>ao,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>wn,IS_SEI_SUPPORTED:()=>uo,IS_SPC_SUPPORTED:()=>Zr,basis:()=>vf,checkSystemRequirementsInternal:()=>Ln,decodeSupportStatus:()=>Pn,encodeSupportStatus:()=>$c,getBrowserInfo:()=>Sf,getDisplayResolution:()=>Ll,isAddTransceiverSupported:()=>ct,isBrowserSupported:()=>Hc,isGetReceiversSupported:()=>ur,isGetSendersSupported:()=>Ji,isGetTransceiversSupported:()=>Gt,isGetUserMediaSupported:()=>wl,isMediaDevicesSupported:()=>kn,isMediaSessionSupported:()=>Vl,isMediaStreamTrackProcessorSupported:()=>If,isReplaceTrackSupported:()=>Gc,isRequestVideoFrameCallbackSupported:()=>lo,isSIMDSupported:()=>Nf,isScreenCaptureApiAvailable:()=>oo,isSelectedCandidatePair:()=>Wi,isSetParametersSupported:()=>co,isSmallStreamAPISupported:()=>Ul,isSmallStreamSupported:()=>no,isStopTransceiverSupported:()=>bf,isTRTCSupported:()=>Af,isUnifiedPlanDefault:()=>yf,isUsedInHttpProtocol:()=>Ti,isWebAudioSupported:()=>xl,isWebCodecSupported:()=>xn,isWebCodecsSupported:()=>Pl,isWebRTCSupported:()=>jc,isWebTransportSupported:()=>Bl});var Fc=Ce(Ml(),1);var _f=1,gf=0,vn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=y.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?Dn.START_MICROPHONE:xc.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?Dn.START_MICROPHONE:xc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Oc(this.version||Te),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,o])=>({uint32_item_key:s,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(te(t))n=Math.floor(e/t);else for(let d=t.length-1;d>0;d--)if(e>t[d]){n=d;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:_f,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(te(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:gf,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},On=(J=>(J[J.enterRoom=500700]="enterRoom",J[J.exitRoom=500701]="exitRoom",J[J.switchRole=500702]="switchRole",J[J.destroy=500703]="destroy",J[J.startLocalAudio=500704]="startLocalAudio",J[J.updateLocalAudio=500705]="updateLocalAudio",J[J.stopLocalAudio=500706]="stopLocalAudio",J[J.startLocalVideo=500707]="startLocalVideo",J[J.updateLocalVideo=500708]="updateLocalVideo",J[J.stopLocalVideo=500709]="stopLocalVideo",J[J.startScreenShare=500710]="startScreenShare",J[J.updateScreenShare=500711]="updateScreenShare",J[J.stopScreenShare=500712]="stopScreenShare",J[J.startRemoteVideo=500713]="startRemoteVideo",J[J.updateRemoteVideo=500714]="updateRemoteVideo",J[J.stopRemoteVideo=500715]="stopRemoteVideo",J[J.muteRemoteAudio=500716]="muteRemoteAudio",J[J.setRemoteAudioVolume=500717]="setRemoteAudioVolume",J[J.use=500718]="use",J[J.sendSEIMessage=5e5]="sendSEIMessage",J[J.sendCustomMessage=500001]="sendCustomMessage",J))(On||{}),Uc=(c=>(c[c.AudioMixer=550700]="AudioMixer",c[c.AIDenoiser=551700]="AIDenoiser",c[c.VirtualBackground=570700]="VirtualBackground",c[c.Beauty=571700]="Beauty",c[c.Watermark=572700]="Watermark",c[c.BasicBeauty=574700]="BasicBeauty",c[c.CDNStreaming=590700]="CDNStreaming",c[c.DeviceDetector=591700]="DeviceDetector",c[c.Debug=592700]="Debug",c))(Uc||{}),Vc=(c=>(c[c.AudioMixer=550701]="AudioMixer",c[c.AIDenoiser=551701]="AIDenoiser",c[c.VirtualBackground=570701]="VirtualBackground",c[c.Beauty=571701]="Beauty",c[c.Watermark=572701]="Watermark",c[c.BasicBeauty=574701]="BasicBeauty",c[c.CDNStreaming=590701]="CDNStreaming",c[c.DeviceDetector=591701]="DeviceDetector",c[c.Debug=592701]="Debug",c))(Vc||{}),Bc=(c=>(c[c.AudioMixer=550702]="AudioMixer",c[c.AIDenoiser=551702]="AIDenoiser",c[c.VirtualBackground=570702]="VirtualBackground",c[c.Beauty=571702]="Beauty",c[c.Watermark=572702]="Watermark",c[c.BasicBeauty=574702]="BasicBeauty",c[c.CDNStreaming=590702]="CDNStreaming",c[c.DeviceDetector=591702]="DeviceDetector",c[c.Debug=592702]="Debug",c))(Bc||{});var Dn=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(Dn||{});var xc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(xc||{});var Ef=new vn(!0),dr=new vn(!1);var v=Ef;var ee={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Tf=new Map([[se,["Firefox",nn]],[Vr,["Edg",cn]],[Wr,["Chrome",An]],[je,["Safari",Vi]],[It,["TBS",ln]],[Bs,["XWEB",hn]],[Br&&or,["WeChat",mn]],[Fs,["QQ(Win)",pn]],[$r,["QQ(Mobile)",xr]],[Fr,["QQ(Mobile X5)",xr]],[$s,["QQ(Mac)",fn]],[Hs,["QQ(iPad)",_n]],[Ws,["MI",gn]],[Js,["HW",En]],[js,["Samsung",Tn]],[Hr,["OPPO",Sn]],[Gr,["VIVO",In]],[Ur,["EDGE",an]],[Us,["SogouMobile",dn]],[Vs,["Sogou",un]]]);function Sf(){let r=Tf.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var Hc=function(){return!(_c||Ur||Vr&&pc<80||se&&mc<56)},Pl=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},kn=function(){if(!navigator.mediaDevices)return Ti()||y.error(Ne.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},kl=!1;function Ti(){return location.protocol==="http:"&&!ui?(kl||y.error(U({key:x.NOT_SUPPORTED_HTTP})),kl=!0,!0):!1}var If=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},$c=function(){return f(this,null,function*(){if(ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ee.detail.isH264EncodeSupported,isVp8EncodeSupported:ee.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),ee.detail.isH264EncodeSupported=i,ee.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:ee.detail.isH264EncodeSupported,isVp8EncodeSupported:ee.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Pn=function(){return f(this,null,function*(){if(ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ee.detail.isH264DecodeSupported,isVp8DecodeSupported:ee.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Ln=Mc(()=>f(void 0,null,function*(){if(ee.result&&ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported&&ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported)return ee;let r=Date.now(),i=Hc(),e=jc(),t=Pl(),s=kn(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield $c(),{isH264DecodeSupported:a,isVp8DecodeSupported:d}=yield Pn();if(!o||!n){let c=yield $c();y.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(c)}`),o=c.isH264EncodeSupported,n=c.isVp8EncodeSupported}if(o&&a&&(Hr||Gr||Ec)&&!It&&ci()<79){let{encode:c,decode:l}=yield Rf();o=c,a=l}return ee.result=i&&e&&s&&(o||n)&&(a||d),ee.detail.isBrowserSupported=i,ee.detail.isWebRTCSupported=e,ee.detail.isWebCodecsSupported=t,ee.detail.isMediaDevicesSupported=s,ee.detail.isScreenShareSupported=oo(),ee.detail.isSmallStreamSupported=no(),ee.detail.isH264EncodeSupported=o,ee.detail.isVp8EncodeSupported=n,ee.detail.isH264DecodeSupported=a,ee.detail.isVp8DecodeSupported=d,ee.result||y.error(`${navigator.userAgent} ${vc(ee.detail,!1)}`),Df(),v.addNumber({key:523800,value:Date.now()-r}),ee})),Af=function(){return ee.result},oo=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Mn=null;function Rf(){return f(this,null,function*(){return Mn||(Mn=new Promise(r=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{y.warn("detectH264Supported start");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),c.close(),l.close(),d.getTracks().forEach(A=>A.stop())},a=setTimeout(()=>{e(),r(i)},2*1e3);let d=t.captureStream(),c=new RTCPeerConnection({}),l=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});c.addEventListener("icecandidate",A=>l.addIceCandidate(A.candidate)),l.addEventListener("icecandidate",A=>c.addIceCandidate(A.candidate)),c.addTrack(d.getVideoTracks()[0],d);let m=yield c.createOffer();yield c.setLocalDescription(m),yield l.setRemoteDescription(m);let p=yield l.createAnswer(),_=Fc.default.parse(p.sdp),I=_.media[0].rtp.findIndex(A=>A.codec==="H264");_.media[0].rtp=[_.media[0].rtp[I]],_.media[0].fmtp=_.media[0].fmtp.filter(A=>A.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(A=>A.payload===_.media[0].rtp[0].payload)),p.sdp=Fc.default.write(_),yield l.setLocalDescription(p),yield c.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let A=yield c.getSenders()[0].getStats(),R=yield l.getReceivers()[0].getStats();i.encode||A.forEach($=>{$.type==="outbound-rtp"&&$.mediaType===h.VIDEO&&$.bytesSent>0&&(i.encode=!0)}),i.decode||R.forEach($=>{$.type==="inbound-rtp"&&$.mediaType===h.VIDEO&&$.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),y.warn(t),r(i)}})).then(r=>((!r.encode||!r.decode)&&y.warn(`detectH264Supported encode: ${r.encode} decode: ${r.decode} ${Tt}`),r)),Mn)})}var Cf=(r,i,e)=>{location.protocol==="http:"&&!ui&&(r[i]=()=>{throw new b({code:S.INVALID_OPERATION,message:Ne.NOT_SUPPORTED_HTTP})})},Wi=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(le(r.selected)&&!r.selected):!1};function Ll(){let r="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${i} * ${e}`}return r}function wl(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function xl(){let r={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){r.isSupported=!0;break}return r.isSupported}function Ul(){return"captureStream"in HTMLCanvasElement.prototype}function no(){return Br||Je||yt&&yt<63?!1:!!(Hc()&&Ul())}var yf=function(){if(E(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:ki}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function ur(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ji(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Gt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ct(){return di===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Zr=(()=>!(!ct()||Ct&&yt<86))();function bf(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ao="RTCRtpSender"in window;function Gc(){return ao&&"replaceTrack"in window.RTCRtpSender.prototype}function co(){return ao&&"setParameters"in window.RTCRtpSender.prototype&&Ji()}var Wc="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Wt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Jc=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Dt=ao&&"createEncodedStreams"in window.RTCRtpSender.prototype&&ci()>=86,wn="RTCRtpScriptTransform"in window,uo=ao&&(Dt||wn),jc=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function xn(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return E(window.AudioDecoder)||(r.AudioDecoder=!0),E(window.AudioEncoder)||(r.AudioEncoder=!0),E(window.VideoDecoder)||(r.VideoDecoder=!0),E(window.VideoEncoder)||(r.VideoEncoder=!0),E(window.ImageDecoder)||(r.ImageDecoder=!0),r}function Vl(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function Bl(){return!E(window.WebTransport)}function Nf(){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 vf(){let r={browser:`${Ut.name}/${Ut.version}`,os:Rn(),displayResolution:Ll(),isScreenShareSupported:oo(),isWebRTCSupported:jc(),isGetUserMediaSupported:wl(),isWebAudioSupported:xl(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:xn(),isMediaSessionSupported:Vl(),isWebTransportSupported:Bl()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var Fl="checkResult";function Df(){Nn.setItem(Fl,{ua:navigator.userAgent,checkResult:ee})}(function(){Ti();let i=Nn.getItem(Fl);i&&i.ua===navigator.userAgent&&(ee=i.checkResult),Ln()})();function lo(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Hl=Ce(Pe(),1);var $l=Symbol("instance"),KE=Symbol("abortCtrl"),Un=Symbol("cacheResult"),ho=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,fo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},mo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Of(r){return typeof r=="object"&&r&&"then"in r}var po=new Map;function he(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let d=po.get(t)||[];po.has(t)||po.set(t,d),d.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...d){let c=this;if(e.context&&(c=H.get(typeof e.context=="function"?e.context.call(this,...d):e.context)),c.state===i)return e.sync?c[Un]:Promise.resolve(c[Un]);c.state instanceof ho&&c.state.action==e.abortAction&&c.state.abort(c);let l=null;Array.isArray(r)?r.length==0?c.state instanceof ho&&c.state.abort(c):(typeof c.state!="string"||!r.includes(c.state))&&(l=new mo(c._state,`${c.name} ${n} to ${i} failed: current state ${c._state} not from ${r.join("|")}`)):r!==c.state&&(l=new mo(c._state,`${c.name} ${n} to ${i} failed: current state ${c._state} not from ${r}`));let m=R=>{if(e.fail&&e.fail.call(this,R),e.sync){if(e.ignoreError)return R;throw R}else return e.ignoreError?Promise.resolve(R):Promise.reject(R)};if(l)return m(l);let p=c.state,_=new ho(p,i,n);fo.call(c,_);let I=R=>{var $;return c[Un]=R,_.aborted||(fo.call(c,i),($=e.success)===null||$===void 0||$.call(this,c[Un])),R},A=R=>{let $=R instanceof Error?R.message:String(R);return fo.call(c,p,R),m(new mo(c._state,`action '${n}' failed :${$}`,R instanceof Error?R:new Error($)))};try{let R=a.apply(this,d);return Of(R)?R.then(I).catch(A):e.sync?I(R):Promise.resolve(I(R))}catch(R){return A(R)}}}}var Mf=(()=>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 fo(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(H.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var H=class extends Hl.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=H.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[$l];s?this.name=s.name+"-"+s.count++:t[$l]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=po.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);po.has(a)&&(a.stateDiagram.forEach(c=>t.add(c)),a.allStates.forEach(c=>n.add(c))),e.forEach(({from:c,to:l,action:m})=>{typeof c=="string"?s.push({from:c,to:l,action:m}):c.length?c.forEach(p=>{s.push({from:p,to:l,action:m})}):o.push({to:l,action:m})}),s.forEach(({from:c,to:l,action:m})=>{n.add(c),n.add(l),n.add(m+"ing"),t.add(`${c} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${c} : ${m} \u{1F534}`)}),o.forEach(({to:c,action:l})=>{t.add(`${l}ing --> ${c} : ${l} \u{1F7E2}`),n.forEach(m=>{m!==c&&t.add(`${m} --> ${l}ing : ${l}`)})});let d=[...t];return Object.defineProperties(i,{stateDiagram:{value:d},allStates:{value:n}}),d}static get(i){let e;return typeof i=="string"?(e=H.instances.get(i),e||H.instances.set(i,e=new H(i,void 0,Object.create(H.prototype)))):(e=H.instances2.get(i),e||H.instances2.set(i,e=new H(i.constructor.name,void 0,Object.create(H.prototype)))),e}static getState(i){var e;return(e=H.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Mf(H.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){fo.call(this,i)}};H.STATECHANGED="stateChanged";H.UPDATEAFSM="updateAFSM";H.INIT="[*]";H.ON="on";H.OFF="off";H.instances=new Map;H.instances2=new WeakMap;var Gl=(window==null?void 0:window.requestIdleCallback)||function(r){let i=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},kf=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Pf=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),_o=class{static generateTaskID(){return this.currentTaskID++}static run(i=Li,e,t){i===rr?t=D({delay:2e3,count:0,backgroundTask:!0},t):i===Pi?t=D({delay:1e4,count:0},t):i===Pr?t=D({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=D({delay:2e3,count:0,backgroundTask:!0},t),bt(e)&&(t=D(D({},t),e)),ie(i)&&(e=i,i=Li);let s=D({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(s.taskID,s),this[i](s),s.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.fps&&(i.delay=+(1e3/i.fps).toFixed(2));let e=new Worker(URL.createObjectURL(new Blob([`
|
|
10
|
+
`,l+=o)),r&&(l+=`
|
|
11
|
+
Refer to: ${ul("en",a)}
|
|
12
|
+
`),l}var kp=Object.prototype.hasOwnProperty;var Vt=s=>typeof s=="function",hi=s=>typeof s=="undefined";var ll=s=>typeof s=="boolean";var Pp=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function hl(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Pp(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(kp.call(s,i))return!1;return!0}}return!1}var Lp=0,xp=1,ml=2;function wp({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,l=0,m=-1,p=Lp,_=(I,A)=>f(this,null,function*(){let C=n||this;try{let F=yield s.apply(C,a);l>0&&o&&o.call(this,l),l=0,I(F)}catch(F){let Pe=()=>{clearTimeout(m),l=0,p=ml,A(F)},Wo=()=>{p!==ml&&l<(Vt(c)?c():c)?(l++,p=xp,Vt(t)&&t.call(this,l,Pe),m=window.setTimeout(()=>{m=-1,_(I,A)},Vt(d)?d(l):d)):(Pe(),Vt(r)&&r.call(this,F))};Vt(e)?e.call(this,{error:F,retry:Wo,reject:A,retryFuncArgs:a,retriedCount:l}):Wo()}});return new Promise(_)}}var Bt=wp;var pl=ye(xe(),1),Up=new pl.default,T=Up;var mi=($=>($.ROOM_DESTROY="1",$.JOIN_START="21",$.JOIN_SCHEDULE_SUCCESS="22",$.JOIN_SIGNAL_CONNECTION_START="23",$.JOIN_SIGNAL_CONNECTION_END="24",$.JOIN_SEND_CMD="25",$.JOIN_RECEIVED_CMD_RES="26",$.JOIN_SUCCESS="27",$.JOIN_FAILED="28",$.LEAVE_START="51",$.LEAVE_SEND_CMD="52",$.LEAVE_SUCCESS="53",$.PUBLISH_START="61",$.SEND_FIRST_VIDEO_FRAME="62",$.PUBLISH_FAILED="63",$.SUBSCRIBE_START="81",$.SUBSCRIBE_SUCCESS="82",$.SUBSCRIBE_FAILED="84",$.UNSUBSCRIBE_SUCCESS="83",$.LOCAL_TRACK_CAPTURE_START="101",$.LOCAL_TRACK_CAPTURE_SUCCESS="102",$.LOCAL_TRACK_CAPTURE_FAILED="103",$.LOCAL_TRACK_PUBLISHED="104",$.LOCAL_TRACK_UNPUBLISHED="105",$.LOCAL_TRACK_REPLACED="106",$.SWITCH_DEVICE_SUCCESS="107",$.TRACK_MUTED="108",$.TRACK_UNMUTED="109",$.REMOTE_TRACK_SUBSCRIBED="110",$.REMOTE_TRACK_UNSUBSCRIBED="111",$.LOCAL_TRACK_RECAPTURE="112",$.PLAY_TRACK_START="151",$.PLAYER_STATE_CHANGED="152",$.VIDEO_LOADED_DATA="153",$.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",$.SIGNAL_CONNECTION_STATE_CHANGED="201",$.PEER_CONNECTION_STATE_CHANGED="202",$.SINGLE_CONNECTION_STAT="203",$.SPC_RECONNECTED="204",$.HEARTBEAT_REPORT="251",$.RECEIVED_PUBLISHED_USER_LIST="252",$.REMOTE_PUBLISH_STATE_CHANGED="253",$.REMOTE_VIDEO_AVAILABLE="254",$.REMOTE_VIDEO_UNAVAILABLE="255",$.REMOTE_AUDIO_AVAILABLE="256",$.REMOTE_AUDIO_UNAVAILABLE="257",$.AUDIO_LEVEL_INTERVAL="260",$.NETWORK_QUALITY="261",$.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",$.QUALITY_LIMITATION_CHANGED="263",$.LOG="264",$))(mi||{});var Cc=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Ie,env:ri.QCLOUD,browserVersion:wt.name+wt.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){di||!y.isAbleToUpload||this._configs.env===ri.QCLOUD&&this.uploadEventToKibana(x(D({},i),{result:"success"}))}logFailedEvent(i){if(di||!y.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||S.UNKNOWN};this._configs.env===ri.QCLOUD&&this.uploadEventToKibana(x(D({},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:qo(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Ie,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
13
|
+
${t.stack}`)),this.sendRequest(Vi(this._configs.sdkAppId,Ni.LOG),r)}sendRequest(i,e){if(!y.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}oi({url:i,body:JSON.stringify(e)}).catch(()=>{})}},K=new Cc;var Rc=null,yc=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(_t).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
14
|
+
`));function $t(s){le(s)&&s!==yc&&(yc=s,y.info(`setIsNeedToSchedule ${s}`))}T.on("28",()=>$t(!0));T.on("63",()=>$t(!0));T.on("84",()=>$t(!0));T.on("201",s=>{s.state==="RECONNECTING"&&$t(!0)});T.on("202",s=>{s.state==="RECONNECTING"&&$t(!0)});function Vp(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=jr(s,h.MAIN),n=jr(s,h.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?h.MAIN:h.BACKUP,d=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),I=Math.round(a.requestStart-a.secureConnectionStart),A=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),F=Math.round(a.responseEnd-a.responseStart),Pe=[_,I,A,C,F];K.uploadEvent({log:`stat-schedule-net:${d}(${l}(${m}->${p})->${Pe.join("->")}) ${c}`,userId:i}),t=x(D({},t),{totalCost:d,local:l,dns:_,tcp:A,tls:I,request:C,response:F});break}}catch(r){y.error("getScheduleDetailCost error",r)}return t}function _l(d){return f(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!yc&&Rc)return{isCached:!0,result:Rc};let l={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(s)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",o),m.append("userSig",String(r)),a&&m.append("role",String(a)),c&&m.append("latencyLevel",String(c)),n&&m.append("frameWorkType",String(n));let p=P(),_=yield $p(m,l,i);_.config&&(_.config.loggerDomain&&Yi(_.config.loggerDomain),le(_.config.scheduleCache)&&$t(!_.config.scheduleCache)),l.delta=P()-p;let I=Vp(Number(i),s,p);return Rc=_,{isCached:!1,result:_,detailCost:I}}catch(m){let p=_e(m)?m[0]:m,_=ee(p.code)?p.code:0,I=`schedule failed${p.message?`: ${p.message}`:""}`,A=new b({code:S.SCHEDULE_FAILED,extraCode:_,message:U({key:w.JOIN_ROOM_FAILED,data:{error:I,code:_}})});throw y.error(I,_),A}})}var Bi={main:"",backup:""};function bc(s){_e(s)?(Bi.main=s[0],Bi.backup=s[1]):Bi.main=s}function jr(s,i=h.MAIN,e=!1){return`https://${Bi[i]||gl(s,i,e)}/api/v1/config`}function El(s,i=h.MAIN){return`https://${Bi[i]||gl(s,i)}/api/v1/trtcAutoConf`}function gl(s,i=h.MAIN,e=!1){if(zs(s))return i===h.MAIN?_t.MAIN_OVERSEA:_t.BACKUP_OVERSEA;let t;return zs(s)?e?t=i===h.MAIN?_t.MAIN_OVERSEA_OLD:_t.BACKUP_OVERSEA_OLD:t=i===h.MAIN?_t.MAIN_OVERSEA:_t.BACKUP_OVERSEA:t=i===h.MAIN?_t.MAIN:_t.BACKUP,t}function Bp(s,i,e){return new Promise((t,r)=>{oi({url:s,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var fl=(s,i)=>Bt({retryFunction:Bp,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function $p(s,i,e){return new Promise((t,r)=>{let o=null;Ys([fl(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=n.message,o||(c>=2&&(d[0]=jr(e,h.MAIN,!0)),a())})(jr(e,h.MAIN),s,{get timeout(){return qr(2+i.count[0])*1e3}}),fl(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=n.message,o||(c>=2&&(d[0]=jr(e,h.BACKUP,!0)),a())})(jr(e,h.BACKUP),s,{get timeout(){return qr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var Fp=function(){return new URLSearchParams(location.search).get("trtc_env")||""},zs=s=>Number(s)<14e8,Vi=function(s,i){let e;vs?e=vs:e=zs(s)?Ga:Ha;let t=Math.floor(Math.random()*Rs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},Ks="unknown";function Sl(){if(Ks!=="unknown")return Ks;let{userAgent:s,connection:i}=navigator,e=(s.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t&&(Ks=Il(t,r)),Ks}function Il(s,i){if(Xo[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Nc(s){Ks=Il(s)}function Qr(){return Xo[Sl()]}function Hp(s,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(s,e,t)}return s}function Gp(s,i=48e3){return Al(s/4,i)}function Al(s,i=48e3){return s*1e3/i}function Wp(s,i=48e3){return Cl(s,i)*4}function Cl(s,i=48e3){return s*i/1e3}var Rl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Ut=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},Ze=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function qr(s,i=1,e=1){return s<=1?e:qr(s-1,e,i+e)}function Ft(s){return s>8?30*1e3:qr(s)*1e3}function Ae(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ie=s=>typeof s=="function",g=s=>typeof s=="undefined",Y=s=>typeof s=="string",ee=s=>typeof s=="number",le=s=>typeof s=="boolean",yt=s=>Ae(s)==="object",_e=s=>Ae(s)==="array",Jp=s=>Ae(s)==="MediaStreamTrack".toLowerCase(),Nt=s=>s.isRemote,or=s=>Ae(s)==="promise",Zs=s=>ie(s)&&s.prototype.constructor===s,yn=s=>Zs(s)?s.prototype.constructor.name:"",jp=typeof AudioWorkletNode!="undefined";function Ys(s){return new Promise((i,e)=>{let t=[];s.forEach(r=>{r.then(i).catch(o=>{t.push(o),t.length===s.length&&e(t)})})})}function P(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Tl=s=>+s<10?`0${s}`:s,qp=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=Tl(e[1])+Tl(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Xp=Object.prototype.hasOwnProperty,{toString:ng}=Object.prototype;function vc(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Ze(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(Xp.call(s,i))return!1;return!0}}return!1}function $i(s,i){return{userId:i,hasAudio:!!(s&Di),hasVideo:!!(s&vi),hasAuxiliary:!!(s&Ki),hasSmall:!!(s&Ds),audioMuted:!!(s&Zo),videoMuted:!!(s&en),audioAvailable:!!(s&Di)&&!(s&Zo),videoAvailable:!!(s&vi)&&!(s&en)}}function Qp(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!g(s.username)&&!g(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",g(s.credentialType)||(i.credentialType=s.credentialType)),i}function eo(s,i=!0){if(!Y(s))return 0;let e=s.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var pi=function(s,i,e,t){if(!(yt(s)&&yt(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(g(i[n])||e&&e.includes(n)))if(yt(s[n])&&yt(i[n]))r+=pi(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=Xr(i[n]),r+=1)}return r};function Xr(s){if(_e(s)){let i=[];return s.forEach((e,t)=>{i[t]=Xr(e)}),i}if(yt(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=Xr(s[e])}),i}return s}var to=s=>{let i=[];if(_e(s))i=[...s];else if(Y(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},zp=s=>Y(s)?document.getElementById(s):s,Yp=s=>{let i=c=>c<10?`0${c}`:`${c}`,e=s.getFullYear(),t=s.getMonth()+1,r=s.getDate(),o=i(s.getHours()),n=i(s.getMinutes()),a=i(s.getSeconds());return`${e}/${t}/${r} ${o}:${n}:${a}`},Kp=()=>Yp(new Date);function bt(s,{keysToInclude:i,keysToExclude:e}){try{if(_e(s))return`[${s.map(n=>bt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Ze(s)||!_e(i)&&!_e(e))return JSON.stringify(s);let t={},r=new Set(i),o=new Set(e);return Object.keys(s).forEach(n=>{(o.size===0&&r.has(n)||r.size===0&&!o.has(n))&&(t[n]=Ze(s[n])||_e(s[n])?JSON.parse(bt(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Dc(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),bt(s,{keysToInclude:e})}function bn(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Oc=()=>{var s,i,e,t;return(s=window.screen)!=null&&s.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},io=s=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(Y(s))t=new Image,t.crossOrigin="anonymous",t.src=s;else if(t=s,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),Mc=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Nn=s=>(Object.keys(s).forEach(i=>{ee(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(Ze(s[i])||_e(s[i]))&&Nn(s[i])}),s);function Fi(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}var kc=(s,i)=>{let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}};function Pc(s,i){let e=new Uint8Array(s.byteLength+i.byteLength);return e.set(new Uint8Array(s),0),e.set(new Uint8Array(i),s.byteLength),e.buffer}function ro(s){return(s&65535)>>>0}function Zp(s){return(s&4294901760)>>>0}var zr=class{constructor(i){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=ll(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),y.log(i,e,hi(this.userId)||hl(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var E=mi;var ef="%cTRTC%c%s",tf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",rf="display: inline",sf=!(We||fe||gc),Lc=class{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!Dr&&!Ns&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&pt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(E.JOIN_FAILED,()=>{this.startUpload()}),T.on(E.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(Y(t.userId)&&ee(t.sdkAppId)){let{userId:r,sdkAppId:o}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:c}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:qo(),sdkAppId:String(a),userId:n,version:Ie,log:c.map(d=>d.log).join(`
|
|
15
|
+
`)}),a),c.forEach(d=>d.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Bt({retryFunction:()=>oi({url:Vi(e,Ni.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(ot());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${pt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){g(pt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(Y(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,o){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};T.emit(E.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,o){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,o),i<this._logLevel)return;let n=((a=pt[i])==null?void 0:a.toLowerCase())||"info";sf?console[n](ef,tf,rf,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new zr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;pt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},y=new Lc;var of=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s=="x"?i:i&3|8).toString(16)})},so=of;var xc=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!ui())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let r=localStorage.getItem(t);if(!r)return!1;let o=JSON.parse(r);if(o&&o.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!ui())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){y.warn(i)}}getItem(i){if(!ui())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){y.warn(e)}}setItem(i,e){if(!!ui())try{let t={expiresIn:Date.now()+Qo,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){y.warn(t)}}deleteItem(i){if(!ui())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return y.warn(e),!1}}clear(){if(!!ui())try{localStorage.clear()}catch(i){y.warn(i)}}},vn=new xc;var Wt={};vr(Wt,{HTTPS_API:()=>Cf,IS_GET_CAPABILITIES_SUPPORTED:()=>qc,IS_GET_SETTINGS_SUPPORTED:()=>Gt,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>jc,IS_INSERTABLE_STREAM_SUPPORTED:()=>vt,IS_RTC_RTP_SENDER_SUPPORTED:()=>co,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Un,IS_SEI_SUPPORTED:()=>lo,IS_SPC_SUPPORTED:()=>Kr,basis:()=>Nf,checkSystemRequirementsInternal:()=>wn,decodeSupportStatus:()=>xn,encodeSupportStatus:()=>Gc,getBrowserInfo:()=>gf,getDisplayResolution:()=>Ll,isAddTransceiverSupported:()=>ct,isBrowserSupported:()=>Wc,isGetReceiversSupported:()=>cr,isGetSendersSupported:()=>Gi,isGetTransceiversSupported:()=>Ht,isGetUserMediaSupported:()=>xl,isMediaDevicesSupported:()=>Ln,isMediaSessionSupported:()=>Vl,isMediaStreamTrackGeneratorSupported:()=>Sf,isMediaStreamTrackProcessorSupported:()=>Tf,isReplaceTrackSupported:()=>Jc,isRequestVideoFrameCallbackSupported:()=>ho,isSIMDSupported:()=>bf,isScreenCaptureApiAvailable:()=>no,isSelectedCandidatePair:()=>Hi,isSetParametersSupported:()=>uo,isSmallStreamAPISupported:()=>Ul,isSmallStreamSupported:()=>ao,isStopTransceiverSupported:()=>yf,isTRTCSupported:()=>If,isUnifiedPlanDefault:()=>Rf,isUsedInHttpProtocol:()=>Ei,isWebAudioSupported:()=>wl,isWebCodecSupported:()=>Vn,isWebCodecsSupported:()=>Pn,isWebRTCSupported:()=>Xc,isWebTransportSupported:()=>Bl});var Hc=ye(kl(),1);var pf=1,ff=0,Dn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=y.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?On.START_MICROPHONE:Vc.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?On.START_MICROPHONE:Vc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Mc(this.version||Ie),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([r,o])=>({uint32_item_key:r,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(!!i&&(this.addEnum({key:i,value:pf,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(ee(e)?t=e:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:ff,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},Mn=(J=>(J[J.enterRoom=500700]="enterRoom",J[J.exitRoom=500701]="exitRoom",J[J.switchRole=500702]="switchRole",J[J.destroy=500703]="destroy",J[J.startLocalAudio=500704]="startLocalAudio",J[J.updateLocalAudio=500705]="updateLocalAudio",J[J.stopLocalAudio=500706]="stopLocalAudio",J[J.startLocalVideo=500707]="startLocalVideo",J[J.updateLocalVideo=500708]="updateLocalVideo",J[J.stopLocalVideo=500709]="stopLocalVideo",J[J.startScreenShare=500710]="startScreenShare",J[J.updateScreenShare=500711]="updateScreenShare",J[J.stopScreenShare=500712]="stopScreenShare",J[J.startRemoteVideo=500713]="startRemoteVideo",J[J.updateRemoteVideo=500714]="updateRemoteVideo",J[J.stopRemoteVideo=500715]="stopRemoteVideo",J[J.muteRemoteAudio=500716]="muteRemoteAudio",J[J.setRemoteAudioVolume=500717]="setRemoteAudioVolume",J[J.use=500718]="use",J[J.sendSEIMessage=5e5]="sendSEIMessage",J[J.sendCustomMessage=500001]="sendCustomMessage",J))(Mn||{}),Bc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(Bc||{}),$c=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))($c||{}),Fc=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(Fc||{});var On=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(On||{});var Vc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(Vc||{});var _f=new Dn(!0),ar=new Dn(!1);var v=_f;var te={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Ef=new Map([[se,["Firefox",an]],[Ur,["Edg",dn]],[Gr,["Chrome",Cn]],[Je,["Safari",wi]],[It,["TBS",hn]],[$s,["XWEB",mn]],[Vr&&rr,["WeChat",pn]],[Fs,["QQ(Win)",fn]],[$r,["QQ(Mobile)",xr]],[Br,["QQ(Mobile X5)",xr]],[Hs,["QQ(Mac)",_n]],[Gs,["QQ(iPad)",En]],[Js,["MI",gn]],[js,["HW",Tn]],[qs,["Samsung",Sn]],[Fr,["OPPO",In]],[Hr,["VIVO",An]],[wr,["EDGE",cn]],[Vs,["SogouMobile",un]],[Bs,["Sogou",ln]]]);function gf(){let s=Ef.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var Wc=function(){return!(Ec||wr||Ur&&fc<80||se&&pc<56)},Pn=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},Ln=function(){if(!navigator.mediaDevices)return Ei()||y.error(Ne.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},Pl=!1;function Ei(){return location.protocol==="http:"&&!di?(Pl||y.error(U({key:w.NOT_SUPPORTED_HTTP})),Pl=!0,!0):!1}var Tf=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Sf=function(){return!!window.MediaStreamTrackGenerator},Gc=function(){return f(this,null,function*(){if(te.detail.isH264EncodeSupported&&te.detail.isVp8EncodeSupported)return{isH264EncodeSupported:te.detail.isH264EncodeSupported,isVp8EncodeSupported:te.detail.isVp8EncodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection,r=document.createElement(h.CANVAS);r.getContext("2d");let o=r.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),s=yield t.createOffer(),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),te.detail.isH264EncodeSupported=i,te.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:te.detail.isH264EncodeSupported,isVp8EncodeSupported:te.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},xn=function(){return f(this,null,function*(){if(te.detail.isH264DecodeSupported&&te.detail.isVp8DecodeSupported)return{isH264DecodeSupported:te.detail.isH264DecodeSupported,isVp8DecodeSupported:te.detail.isVp8DecodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection;return s=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},wn=kc(()=>f(void 0,null,function*(){if(te.result&&te.detail.isH264EncodeSupported&&te.detail.isVp8EncodeSupported&&te.detail.isH264DecodeSupported&&te.detail.isVp8DecodeSupported)return te;let s=Date.now(),i=Wc(),e=Xc(),t=Pn(),r=Ln(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield Gc(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield xn();if(!o||!n){let d=yield Gc();y.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(d)}`),o=d.isH264EncodeSupported,n=d.isVp8EncodeSupported}if(o&&a&&(Fr||Hr||Tc)&&!It&&ai()<79){let{encode:d,decode:l}=yield Af();o=d,a=l}return te.result=i&&e&&r&&(o||n)&&(a||c),te.detail.isBrowserSupported=i,te.detail.isWebRTCSupported=e,te.detail.isWebCodecsSupported=t,te.detail.isMediaDevicesSupported=r,te.detail.isScreenShareSupported=no(),te.detail.isSmallStreamSupported=ao(),te.detail.isH264EncodeSupported=o,te.detail.isVp8EncodeSupported=n,te.detail.isH264DecodeSupported=a,te.detail.isVp8DecodeSupported=c,te.result||y.error(`${navigator.userAgent} ${Dc(te.detail,!1)}`),vf(),v.addNumber({key:523800,value:Date.now()-s}),te})),If=function(){return te.result},no=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},kn=null;function Af(){return f(this,null,function*(){return kn||(kn=new Promise(s=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{y.warn("detectH264Supported start");let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),d.close(),l.close(),c.getTracks().forEach(A=>A.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),l=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",A=>l.addIceCandidate(A.candidate)),l.addEventListener("icecandidate",A=>d.addIceCandidate(A.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield l.setRemoteDescription(m);let p=yield l.createAnswer(),_=Hc.default.parse(p.sdp),I=_.media[0].rtp.findIndex(A=>A.codec==="H264");_.media[0].rtp=[_.media[0].rtp[I]],_.media[0].fmtp=_.media[0].fmtp.filter(A=>A.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(A=>A.payload===_.media[0].rtp[0].payload)),p.sdp=Hc.default.write(_),yield l.setLocalDescription(p),yield d.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let A=yield d.getSenders()[0].getStats(),C=yield l.getReceivers()[0].getStats();i.encode||A.forEach(F=>{F.type==="outbound-rtp"&&F.mediaType===h.VIDEO&&F.bytesSent>0&&(i.encode=!0)}),i.decode||C.forEach(F=>{F.type==="inbound-rtp"&&F.mediaType===h.VIDEO&&F.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),y.warn(t),s(i)}})).then(s=>((!s.encode||!s.decode)&&y.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${Tt}`),s)),kn)})}var Cf=(s,i,e)=>{location.protocol==="http:"&&!di&&(s[i]=()=>{throw new b({code:S.INVALID_OPERATION,message:Ne.NOT_SUPPORTED_HTTP})})},Hi=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(le(s.selected)&&!s.selected):!1};function Ll(){let s="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";s+=`${i} * ${e}`}return s}function xl(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function wl(){let s={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){s.isSupported=!0;break}return s.isSupported}function Ul(){return"captureStream"in HTMLCanvasElement.prototype}function ao(){return Vr||We||Rt&&Rt<63?!1:!!(Wc()&&Ul())}var Rf=function(){if(g(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:Oi}),s.addTransceiver(h.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function cr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Gi(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Ht(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ct(){return ci===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Kr=(()=>!(!ct()||Ct&&Rt<86))();function yf(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var co="RTCRtpSender"in window;function Jc(){return co&&"replaceTrack"in window.RTCRtpSender.prototype}function uo(){return co&&"setParameters"in window.RTCRtpSender.prototype&&Gi()}var jc="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Gt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,qc=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,vt=co&&"createEncodedStreams"in window.RTCRtpSender.prototype&&ai()>=86,Un="RTCRtpScriptTransform"in window,lo=co&&(vt||Un),Xc=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Vn(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(s.AudioDecoder=!0),g(window.AudioEncoder)||(s.AudioEncoder=!0),g(window.VideoDecoder)||(s.VideoDecoder=!0),g(window.VideoEncoder)||(s.VideoEncoder=!0),g(window.ImageDecoder)||(s.ImageDecoder=!0),s}function Vl(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function Bl(){return!g(window.WebTransport)}function bf(){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 Nf(){let s={browser:`${wt.name}/${wt.version}`,os:Rn(),displayResolution:Ll(),isScreenShareSupported:no(),isWebRTCSupported:Xc(),isGetUserMediaSupported:xl(),isWebAudioSupported:wl(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Vn(),isMediaSessionSupported:Vl(),isWebTransportSupported:Bl()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var $l="checkResult";function vf(){vn.setItem($l,{ua:navigator.userAgent,checkResult:te})}(function(){Ei();let i=vn.getItem($l);i&&i.ua===navigator.userAgent&&(te=i.checkResult),wn()})();function ho(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Hl=ye(xe(),1);var Fl=Symbol("instance"),Yg=Symbol("abortCtrl"),Bn=Symbol("cacheResult"),mo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,_o.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},po=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Df(s){return typeof s=="object"&&s&&"then"in s}var fo=new Map;function he(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let c=fo.get(t)||[];fo.has(t)||fo.set(t,c),c.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=H.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[Bn]:Promise.resolve(d[Bn]);d.state instanceof mo&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;Array.isArray(s)?s.length==0?d.state instanceof mo&&d.state.abort(d):(typeof d.state!="string"||!s.includes(d.state))&&(l=new po(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${s.join("|")}`)):s!==d.state&&(l=new po(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${s}`));let m=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(l)return m(l);let p=d.state,_=new mo(p,i,n);_o.call(d,_);let I=C=>{var F;return d[Bn]=C,_.aborted||(_o.call(d,i),(F=e.success)===null||F===void 0||F.call(this,d[Bn])),C},A=C=>{let F=C instanceof Error?C.message:String(C);return _o.call(d,p,C),m(new po(d._state,`action '${n}' failed :${F}`,C instanceof Error?C:new Error(F)))};try{let C=a.apply(this,c);return Df(C)?C.then(I).catch(A):e.sync?I(C):Promise.resolve(I(C))}catch(C){return A(C)}}}}var Of=(()=>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 _o(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(H.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var H=class extends Hl.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=H.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[Fl];r?this.name=r.name+"-"+r.count++:t[Fl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=fo.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);fo.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?r.push({from:d,to:l,action:m}):d.length?d.forEach(p=>{r.push({from:p,to:l,action:m})}):o.push({to:l,action:m})}),r.forEach(({from:d,to:l,action:m})=>{n.add(d),n.add(l),n.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),o.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),n.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=H.instances.get(i),e||H.instances.set(i,e=new H(i,void 0,Object.create(H.prototype)))):(e=H.instances2.get(i),e||H.instances2.set(i,e=new H(i.constructor.name,void 0,Object.create(H.prototype)))),e}static getState(i){var e;return(e=H.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Of(H.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){_o.call(this,i)}};H.STATECHANGED="stateChanged";H.UPDATEAFSM="updateAFSM";H.INIT="[*]";H.ON="on";H.OFF="off";H.instances=new Map;H.instances2=new WeakMap;var Gl=(window==null?void 0:window.requestIdleCallback)||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},Mf=(window==null?void 0:window.cancelIdleCallback)||function(s){clearTimeout(s)},kf=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Eo=class{static generateTaskID(){return this.currentTaskID++}static run(i=ki,e,t){i===tr?t=D({delay:2e3,count:0,backgroundTask:!0},t):i===Mi?t=D({delay:1e4,count:0},t):i===Ps?t=D({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=D({delay:2e3,count:0,backgroundTask:!0},t),yt(e)&&(t=D(D({},t),e)),ie(i)&&(e=i,i=ki);let r=D({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.fps&&(i.delay=+(1e3/i.fps).toFixed(2));let e=new Worker(URL.createObjectURL(new Blob([`
|
|
16
16
|
let timerID = null;
|
|
17
17
|
self.onmessage = function (e) {
|
|
18
18
|
if (e.data === 'start') {
|
|
@@ -23,13 +23,13 @@ ${t.stack}`)),this.sendRequest(Fi(this._configs.sdkAppId,Di.LOG),s)}sendRequest(
|
|
|
23
23
|
clearInterval(timerID);
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
|
-
`],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=P(),t,s=()=>{if(t=P()-e,t>=i.delay&&(e=P()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=Gl(s,{timeout:i.delay})};return i.ricID=Gl(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=P(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=P()-e,e=P(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=P()-e,t>=i.delay&&(e=P()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let o=()=>{if(document.hidden){let n=P()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Pf(s),o&&kf(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};_o.taskMap=new Map,_o.currentTaskID=1;var Q=_o;var sT={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:h.SEI_MESSAGE,ERROR:"error"};var Ae={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",TIME_UPDATED:"time-updated"};var jt={};vr(jt,{create:()=>we,remove:()=>ge});var go=new WeakMap;function we(r,i){go.has(r)||go.set(r,[]);let e=go.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function ge(r){let i=go.get(r);i&&(i.forEach(e=>e()),go.delete(r))}var qt=new WeakMap;function qe({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=Ft({retryFunction:n.value,settings:r,onError({error:d,retry:c,reject:l,retryFuncArgs:m}){var p;i?i.call(this,d,()=>{var _;(_=qt.get(s))!=null&&_.has(o)?c():l(d)},l,m):(p=qt.get(s))!=null&&p.has(o)?c():l(d)},onRetrying(d,c){var l;Bt(e)&&e.call(this,d,c),(l=qt.get(s))!=null&&l.has(o)&&(qt.get(s).get(o).stopRetry=c)},onRetryFailed:t});return n.value=function(...d){let c=qt.get(s);return c?c.set(o,{args:d}):qt.set(s,new Map([[o,{args:d}]])),a.apply(this,d).finally(()=>{var l;return(l=qt.get(s))==null?void 0:l.delete(o)})},n}}function Eo({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var d,c;if((d=qt.get(t))!=null&&d.has(r)){let{stopRetry:l,args:m}=qt.get(t).get(r),p=!0;if(e){for(let _ of m)if(!a.find(I=>I===_)){p=!1;break}}p&&(i&&i.apply(this,a),l&&l(),(c=qt.get(t))==null||c.delete(r))}return n.apply(this,a)},o}}var Xt=class extends H{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");u(this,"_delayDestroyTimeoutId",0);u(this,"_isReplayByRecreateMediaStreamCalled",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ka,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){return this._state==="PAUSED"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=U({key:x.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new b({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this.isStopped||(this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&Q.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.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Tc?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 we(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);jt==null||jt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){T.on(g.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&ge(this.track)}unbindEvents(){this.element&&ge(this.element),this.unbindTrackEvents(),T.off(g.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(Q.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.stop();break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),Je&&(this._interval=Q.run(Li,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:s,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${o} userAgent: ${navigator.userAgent}`),Z.uploadEvent({log:`stat-${this.kind}-${We.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(Ae.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(Ae.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,s)=>{Gi(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),s((a=this.element)==null?void 0:a.error)}),Gi(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&s((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.stop();break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){return e}handlePaused(e){return e}handleStopped(e){return e}getElement(){return this.element}};N([qe({settings:{retries:2,timeout:0},onError(r,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],Xt.prototype,"doReplayByRecreateMediaStream",1),N([he([],"PLAYING",{sync:!0,success(r){this.emit(Ae.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:r})}})],Xt.prototype,"handlePlaying",1),N([he("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(r){this.emit(Ae.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:r})}})],Xt.prototype,"handlePaused",1),N([he([],"STOPPED",{sync:!0,success(r){this.emit(Ae.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:r})}})],Xt.prototype,"handleStopped",1);var Si="trtc_autoplay",qc=`${Si}_mask`,es=`${Si}_wrapper`,Wl=`${Si}_header`,Xc=`${Si}_content`,Vn=`${Si}_action_wrapper`,Qc=`${Si}_question`,zc=`${Si}_collapse`,Bn=`${Si}_action_confirm`,Jl=`${Si}_detail`,jl="#2473E8",Kc="dialog",Lf=`${Kc}-show`,wf=`${Kc}-1`,xf=`${Kc}-2`,ql=!1,Zc=()=>!!document.querySelector(`.${es}`),Ql=`${wt}/${Vt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Xl=`<br><a href='${Ql}' target='_blank'>${Vt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Uf=`${Vt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${Xl}`:`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. ${Xl}`}`,Yc=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(Vt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!ql){let i=document.createElement("style");i.innerHTML=`.${qc}{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;}.${qc} div:not(.${Vn}){display:block !important;}.${es}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${es} a{color:${jl};}.${Wl}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Xc}{margin:8px 0;}.${Vn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${zc}{margin-right:auto;cursor:pointer}.${Qc}{height:100%;line-height:16px;cursor:pointer;}.${Bn}{margin-left:8px;color:#fff;background:${jl};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Bn}:hover{opacity:0.9;}.${zc},.${Bn},.${Xc},.${Qc}{font-size:14px;}@media screen and (max-width:750px){.${es}{width:80vw;}}`,document.head.appendChild(i),ql=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${qc}"><div class='${es}'><div class='${Wl}'>${location.host}</div><div class='${Xc}'>${this.content}</div><div class='${Jl}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Uf}</div><div class='${Vn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Bn,e.innerText=Vt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Qc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
|
+
`],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=P(),t,r=()=>{if(t=P()-e,t>=i.delay&&(e=P()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=Gl(r,{timeout:i.delay})};return i.ricID=Gl(r,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=P(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=P()-e,e=P(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=P()-e,t>=i.delay&&(e=P()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=P()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),r&&kf(r),o&&Mf(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};Eo.taskMap=new Map,Eo.currentTaskID=1;var Z=Eo;var rT={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:h.SEI_MESSAGE,ERROR:"error"};var Re={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",TIME_UPDATED:"time-updated"};var Jt={};vr(Jt,{create:()=>Ue,remove:()=>Ee});var go=new WeakMap;function Ue(s,i){go.has(s)||go.set(s,[]);let e=go.get(s),r={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),r)};return r}function Ee(s){let i=go.get(s);i&&(i.forEach(e=>e()),go.delete(s))}var jt=new WeakMap;function je({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Bt({retryFunction:n.value,settings:s,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){var p;i?i.call(this,c,()=>{var _;(_=jt.get(r))!=null&&_.has(o)?d():l(c)},l,m):(p=jt.get(r))!=null&&p.has(o)?d():l(c)},onRetrying(c,d){var l;Vt(e)&&e.call(this,c,d),(l=jt.get(r))!=null&&l.has(o)&&(jt.get(r).get(o).stopRetry=d)},onRetryFailed:t});return n.value=function(...c){let d=jt.get(r);return d?d.set(o,{args:c}):jt.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=jt.get(r))==null?void 0:l.delete(o)})},n}}function To({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,d;if((c=jt.get(t))!=null&&c.has(s)){let{stopRetry:l,args:m}=jt.get(t).get(s),p=!0;if(e){for(let _ of m)if(!a.find(I=>I===_)){p=!1;break}}p&&(i&&i.apply(this,a),l&&l(),(d=jt.get(t))==null||d.delete(s))}return n.apply(this,a)},o}}var qt=class extends H{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");u(this,"_delayDestroyTimeoutId",0);u(this,"_isReplayByRecreateMediaStreamCalled",!1);u(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ka,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){return this._state==="PAUSED"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=U({key:w.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new b({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this.isStopped||(this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&Z.clearTask(this._interval))}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Sc?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 Ue(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);Jt==null||Jt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){T.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&Ee(this.track)}unbindEvents(){this.element&&Ee(this.element),this.unbindTrackEvents(),T.off(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(Z.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.stop();break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),We&&(this._interval=Z.run(ki,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),K.uploadEvent({log:`stat-${this.kind}-${Ge.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(Re.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),K.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),K.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(Re.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Fi(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Fi(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.stop();break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){return e}handlePaused(e){return e}handleStopped(e){return e}getElement(){return this.element}};N([je({settings:{retries:2,timeout:0},onError(s,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],qt.prototype,"doReplayByRecreateMediaStream",1),N([he([],"PLAYING",{sync:!0,success(s){this.emit(Re.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:s})}})],qt.prototype,"handlePlaying",1),N([he("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(s){this.emit(Re.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:s})}})],qt.prototype,"handlePaused",1),N([he([],"STOPPED",{sync:!0,success(s){this.emit(Re.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:s})}})],qt.prototype,"handleStopped",1);var gi="trtc_autoplay",Qc=`${gi}_mask`,Zr=`${gi}_wrapper`,Wl=`${gi}_header`,zc=`${gi}_content`,$n=`${gi}_action_wrapper`,Yc=`${gi}_question`,Kc=`${gi}_collapse`,Fn=`${gi}_action_confirm`,Jl=`${gi}_detail`,jl="#2473E8",ed="dialog",Pf=`${ed}-show`,Lf=`${ed}-1`,xf=`${ed}-2`,ql=!1,td=()=>!!document.querySelector(`.${Zr}`),Ql=`${Lt}/${Ut()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Xl=`<br><a href='${Ql}' target='_blank'>${Ut()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,wf=`${Ut()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${Xl}`:`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. ${Xl}`}`,Zc=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(Ut()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!ql){let i=document.createElement("style");i.innerHTML=`.${Qc}{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;}.${Qc} div:not(.${$n}){display:block !important;}.${Zr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Zr} a{color:${jl};}.${Wl}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${zc}{margin:8px 0;}.${$n}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Kc}{margin-right:auto;cursor:pointer}.${Yc}{height:100%;line-height:16px;cursor:pointer;}.${Fn}{margin-left:8px;color:#fff;background:${jl};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Fn}:hover{opacity:0.9;}.${Kc},.${Fn},.${zc},.${Yc}{font-size:14px;}@media screen and (max-width:750px){.${Zr}{width:80vw;}}`,document.head.appendChild(i),ql=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Qc}"><div class='${Zr}'><div class='${Wl}'>${location.host}</div><div class='${zc}'>${this.content}</div><div class='${Jl}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${wf}</div><div class='${$n}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Fn,e.innerText=Ut()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Yc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
27
|
<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">
|
|
28
28
|
<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"/>
|
|
29
29
|
<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"/>
|
|
30
30
|
<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"/>
|
|
31
31
|
</svg>
|
|
32
|
-
`,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=zc,s.innerText=`${Vt()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${Vn}`);return n.appendChild(s),n.appendChild(t),n.appendChild(e),o}addDiaLog(){Zc()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${es}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",y.info("show autoplay dialog"),Z.uploadEvent({log:Lf}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){y.warn("confirm clicked, try resume stream"),T.emit(g.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Jl}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Z.uploadEvent({log:wf}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ql,"_blank"),this._isQuestionClicked||Z.uploadEvent({log:xf}),this._isQuestionClicked=!0}},Fn=Yc;var tt=class extends Xt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!Zc()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let o=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=o.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!o.includes("scaleX")&&(this.element.style.transform=`${o} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Ae.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function lr(r,i){return f(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),y.info("worklet addModule success")}catch(e){throw y.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var hr=new window.AudioContext({sampleRate:48e3}),$n=()=>{hr.state==="suspended"?(hr.resume(),document.addEventListener("click",$n)):hr.state==="interrupted"?hr.resume():document.removeEventListener("click",$n)};document.addEventListener("click",$n);hr.onstatechange=()=>{y.info(`context state: ${hr.state}`),$n()};var xe=r=>hr;var dt=class{constructor(){u(this,"node");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set);u(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.node&&(this.node.channelCount=i),this.next.forEach(e=>e.channelCount=i)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(t){y.error(t),v.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){y.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},Hn=class extends dt{constructor(e=256){super();this.fftSize=e;u(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,s=0,o=0,n=`M${s},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${s},${o}`,s+=t;return n}},To=class{constructor(){u(this,"source",new dt);u(this,"gain",new dt);u(this,"destination",new dt)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(ed(i))}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ts=class extends To{constructor(e){super();this.context=e;u(this,"denoiser",new dt);this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},Gn=class{constructor(){u(this,"audioContext",xe("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(this,"mixWeight",0)}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zl=new WeakMap;function ed(r){let i=zl.get(r);if(i)return i;let e=xe();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return zl.set(r,i),i}window.AudioWorkletProcessor||(window.AudioWorkletProcessor=class{constructor(){u(this,"port")}});var td=class 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=i=>{let{data:e}=i;switch(e.name){case"chunk":this.cache.push.apply(this.cache,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;break}}}process(i,e){let t=i[0],s=e[0];if(!t&&!s)return!0;if(this.isStop)return!1;let o=s?s[0].length:0,n=this.cache.length;n>o?(s[0].set(this.cache.slice(0,o)),this.cache=this.cache.slice(o)):this.unmute&&s[0].set(t[0]);let a=n>o?s[0]:t[0];if(!a)return!0;let d=0;for(let c=0;c<a.length;++c)d=Math.max(Math.abs(a[c]),d);return this.volume=d,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:n,outputLen:o})),!0}},id=td.toString();delete window.AudioWorkletProcessor;var Qt=class{constructor(i){this._volume=0;this._scriptProcessorNode=null;this._audioWorkletNode=null;this._interval=200;this.ready=this.preload();let{log:e}=i;this._log=e,T.on(g.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Qt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Qt.workletReady){let i=`${id.slice(0,5)} VolumeMeterWorklet ${id.slice(6)};registerProcessor('volume-meter', VolumeMeterWorklet);`;Qt.workletReady=lr(Qt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Qt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Qt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Qt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),Z.logFailedEvent({userId:this._log.userId,eventType:We.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=xe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Qt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(g.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},is=Qt;is.lastMessageTime=0,is.audioContext=xe("volume-meter");var Wn=class extends dt{constructor(e){super();this._volumeMeter=new is(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}},rd=is;var eh=Ce(Pe(),1);var Kl=r=>i=>i.deviceId===r;var So=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&rs(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Kl(s.deviceId))){let o=`${this.kind}${this.type}Added`;y.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Kl(s.deviceId))){let o=`${this.kind}${this.type}Removed`;y.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},sd=class extends eh.EventEmitter{constructor(){super();u(this,"audioInputs",new So(h.AUDIO));u(this,"videoInputs",new So(h.VIDEO));u(this,"audioOutputs",new So(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Q.run(rr,()=>{this.update()},{delay:1e4}))}init(){Jn().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 Jn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Re=Ns||Dr?null:new sd;function rs(r){return r.deviceId===r.groupId&&r.groupId===""}function Jn(){return f(this,arguments,function*(r=0){if(Ti()||!kn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{rs(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){y.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&od.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Xe(r=!1){return Re.update(r?1:0).then(i=>i.audioInputs.devices)}function it(r=!1){return Re.update(r?2:0).then(i=>i.videoInputs.devices)}var Zl=!1;function th(){return f(this,null,function*(){try{Zl||(Zl=!0,y.info(`speakers:${(yield ji()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function ji(r=!1){return f(this,null,function*(){return Re.update(r?1:0).then(i=>i.audioOutputs.devices)})}var od=new Set;function ih(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!od.has(t)}function rh(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!od.has(t)}function nd(r,i){return f(this,null,function*(){let t=(yield Xe()).find(s=>s.deviceId===ir);return!i&&(t==null?void 0:t.groupId)===r||(t==null?void 0:t.groupId)===r&&t.label===i})}function sh(o){return f(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===ir?yield nd(e,t):!0})}var jn,ad=class extends To{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new Hn);this.volumeMeter=new Wn({log:this.log}),this.volumeDestination=new dt,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},qi=class extends Xt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",xe("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");e.url&&(this.url=e.url),this.pipeline=new ad(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(){if((Bi==="15.2"||Bi==="15.3"||Bi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=jn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.url&&(t.crossOrigin="anonymous",t.src=this.url),t.ontimeupdate=()=>{this.emit(Ae.TIME_UPDATED,this.currentTime)},this.element=t,t===jn&&(jn=void 0),this.bindElementEvents()}play(){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(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(xe("player").createAnalyser()),this.setVolume(this._volume),th(),ye(qi.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},qn=class extends qi{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Ae.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}},Xn=class extends qi{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new dt);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this._output.setNode(xe("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Ae.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ge(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&Jr&&(jn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var mr=class extends H{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Xn:tt}){var a;super();u(this,"id",ro());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=y.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof rt?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof rt}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Ae.PLAYER_STATE_CHANGED,d=>{T.emit(g.PLAYER_STATE_CHANGED,D({track:this},d)),this.emit("player-state-changed",d)}),this.kind===h.VIDEO&&(this.player.on(Ae.LOADED_DATA,()=>{T.emit(g.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Ae.MEDIA_TRACK_CHANGED,d=>{var c;(c=this.subVideoPlayerMap)==null||c.forEach(l=>l.setTrack(d))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Ae.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||y}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let s=_e(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!E(t.muted)&&this.setPlayerMute(t.muted),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof tt&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),_e(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!E(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof tt&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof tt&&this.player.setContainer(s)),T.emit(g.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(),_e(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(le(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(d=>n===d)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new tt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let o of s)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(vt(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),T.emit(e?g.TRACK_MUTED:g.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){we(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ge(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._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(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(vt(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Fn;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof tt?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};N([he([],H.INIT,{sync:!0})],mr.prototype,"close",1);var Vf=Object.prototype.hasOwnProperty,{toString:XS}=Object.prototype;function Bf(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(et(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(Vf.call(r,i))return!1;return!0}}return!1}var zt=Bf;var Ff=function(r){return f(this,null,function*(){let i=Hf(r);y.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Xe(),y.info(`microphones: ${Nt(e,{keysToInclude:s})}`)),i.video&&(t=yield it(),y.info(`cameras: ${Nt(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Jc&&o.getTracks().forEach(n=>{y.info(`${n.kind} capabilities: ${Nt(n.getCapabilities(),{keysToInclude:tn})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=U({key:x.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=U({key:x.MICROPHONE_NOT_FOUND}))),new b({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},$f=Ft({retryFunction:Ff,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!je||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&oh(t[0].microphoneId,!1),t[0].cameraId&&oh(t[0].cameraId,!0)},onRetrying:r=>{y.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Z.logFailedEvent({eventType:We.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Z.logSuccessEvent({eventType:We.GET_USER_MEDIA_RETRY}),Z.uploadEvent({log:`stat-${We.GET_USER_MEDIA_RETRY}-success-${r}`})}});function oh(r,i){return f(this,null,function*(){let t=(i?yield it():yield Xe()).find(s=>s.deviceId===r);t&&ie(t.getCapabilities)&&y.warn(Nt(t.getCapabilities(),{keysToInclude:tn}))})}function Hf(r){return{audio:Gf(r),video:Wf(r)}}function Gf(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!zt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(te(r.channelCount)&&(i.channelCount=r.channelCount),le(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),le(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),le(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),zt(i)?!0:i)}function Wf(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!zt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!se&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!se&&(e.height.max=r.height)),se&&Rt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),zt(e)?!0:e)}var nh=$f;function Qn(r){return j((i,e)=>function(...t){return f(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function Ot(r){return j((i,e)=>function(...t){return f(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function j(r){return function(i,e,t){return t.value=r(t.value,e),t}}var ah=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&y.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{y.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Jf=0,zn=class{constructor(){this.log=y.createLogger({id:`fq${++Jf}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=D({},i),s=new Promise((a,d)=>{t.resolve=a,t.reject=d});return t.promise=s,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Io=new WeakMap,Yn=new WeakMap;function Yt(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=Io.get(this)||new zn;return Io.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function ch(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=Io.get(this);if(n){let a=n.queue.filter((d,c)=>{if(c===0)return!0;let l=!0;return d.args.forEach(m=>{o.find(p=>p===m)||(l=!1)}),l?(d.reject(new b({code:S.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Kn(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,d,c;let n=[];return(d=(a=Io.get(this))==null?void 0:a.queue)==null||d.forEach(l=>n.push(l)),(c=Yn.get(this))==null||c.forEach(l=>l==null?void 0:l.queue.forEach(m=>n.push(m))),n.forEach(l=>{l.reject(new b({code:S.API_CALL_ABORTED,message:r}))}),Io.delete(this),Yn.delete(this),s.apply(this,o)},t}}function Ii(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=Yn.get(this)||new Map,d=a.get(o(n))||new zn;return a.set(o(n),d),Yn.set(this,a),d.push({fn:s,args:n,context:this})},t}}function Qe(r,i){return j((e,t)=>function(...s){let o=r;try{let n=e.apply(this,s),a=P();return ar(n)?n.then(d=>(i?v.addSuccessEvent({key:o,cost:P()-a}):v.addSuccessEvent({key:o}),d)).catch(d=>{throw v.addFailedEvent({key:o,error:d}),d}):(v.addSuccessEvent({key:o}),n)}catch(n){throw v.addFailedEvent({key:o,error:n}),n}})}var cd=class extends mr{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){we(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ge(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let s=P();T.emit(g.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield nh(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(g.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:P()-s}),o}catch(s){throw T.emit(g.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===H.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(g.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&Wt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield sh({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),Jn().then(n=>{let a=n.find(d=>d.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!rh(this.mediaTrack)||this.kind===h.VIDEO&&!ih(this.mediaTrack)||this._isRecapturing||e&&Rt&&je)}onTrackMuted(){if(super.onTrackMuted(),ah(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<kr){setTimeout(()=>this.onTrackMuted(),kr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Je||fe)&&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(ye(cd.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<kr){setTimeout(()=>this.onTrackEnded(),kr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Xe():yield it()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),T.emit(g.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),T.emit(g.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof me;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Ao.get(t)||0)+1;if(Ao.set(t,s),s>=3){let o=e?(yield it()).find(n=>!Ao.has(n.deviceId)):(yield Xe()).find(n=>!Ao.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},rt=cd;N([he(H.INIT,"capture",{ignoreError:!0,sync:!0})],rt.prototype,"setStateToCapture",1),N([Yt()],rt.prototype,"capture",1),N([he("capture","publish",{ignoreError:!0,success(){var i,e;this.room.localTracks.add(this),T.emit(g.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((e=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:e.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var s,o;if(!((((o=(s=this.room)==null?void 0:s.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let n=this.kind===h.AUDIO,a=this.stat.bytesSent>0;v[a?"addSuccessEvent":"addFailedEvent"]({key:n?503700:513702}),a||(v.addEnum({key:n?503701:513703,value:Xs()}),Z.uploadEvent({log:`stat-encode-failed-${this.kind}-${nr()||hi()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}}),Qe(521714,!1)],rt.prototype,"publish",1),N([j(r=>function(){return f(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),he([],"capture",{sync:!0})],rt.prototype,"unpublish",1);var Ao=new Map;T.on(g.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Ao.delete(r.track.deviceId)});var Ue=class extends rt{constructor(e){super(1,qn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"codecPipeline",[]);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new ts(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){yield ye(Ue.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return f(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===ir){if(yield nd(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),this.room&&(yield this.room.replaceTrack(this)),T.emit(g.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(){Re&&!Re.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Re.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),de(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Xe();t[0]?this.recapture(t[0].deviceId):Re.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!E(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(yt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),Re.off("audioInputAdded",this.handleMicrophoneAdded,this),Re.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield ye(Ue.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield ye(Ue.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}encodeFrame(e){if(!this.manager)return e;let t=At?-100:0;return this.manager.encodePipeline.reduce((s,o)=>o?o({frame:s,ntpTime:$e()+t}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Ri=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var Zn=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ri(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),c=new DataView(d),l=new DataView(i.data),m=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)c.setInt8(m++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)c.setInt8(m++,l.getInt8(p));return i.data=d,n.length}return 0}};var me=class extends rt{constructor(e,t=4){super(t,tt);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new Zn);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(w(D({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Wt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,s,o;if(K(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,ye(me.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,ye(me.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=D({},e),s=t.width>t.height;t.width*t.height<=160*120&&fe&&Ct&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Sc&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(w(D({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Wt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Dc()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(g.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){Re&&!Re.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Re.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),de(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield it();t[0]?this.recapture(t[0].deviceId):Re.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let s=t?8:this.mediaType;return this.manager.encodePipeline.reduce((o,n)=>n?n({frame:o,mediaType:s}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return f(this,null,function*(){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),ye(me.prototype,this,"play").call(this,e,t)})}close(){Re.off("videoInputAdded",this.handleCameraAdded,this),Re.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield ye(me.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield it()).find(o=>o.deviceId!==e);if(s)yield ye(me.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var uh=ro();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:uh,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var Qf=function(r){return f(this,null,function*(){let i=null,e=Kf(r);y.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Wr&&yt<74||je||se)&&y.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){y.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield zf(s,r.captureElement))}if(r.audio){let o=Yf(r);y.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function zf(r,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ie(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===uh))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){y.warn(`cropTo target failed ${t}`)}})}function Yf(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return E(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function Kf(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:je?{max:r.width}:{ideal:r.width,max:r.width},height:je?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var lh=Qf;var st=class extends me{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:c}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):m=yield lh({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:d,preferDisplaySurface:c}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof b?m:new b({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};var Kt=class extends Ue{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Zf="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",dd;function Ro(r){return f(this,null,function*(){let i=xe("dump");dd||(dd=lr(i,URL.createObjectURL(new Blob([Zf],{type:"application/javascript"})))),yield dd;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}function hh({frame:r,ntpTime:i}){let e=new ArrayBuffer(4),t=new DataView(e);t.setUint16(0,10003),t.setUint16(2,_i(i));let s=io(e,r.data);return r.data=s,r}function mh({frame:r,onAudioFrameNTPTime:i,onAudioLeaving:e}){let t=new DataView(r.data);if(t.getUint16(0)===65570&&(e==null||e(),r.data=r.data.slice(2),t=new DataView(r.data)),t.getUint16(0)===10003)if(t.getUint8(2)===0){let s=t.getUint16(3);r.data=r.data.slice(5),i==null||i(s,r)}else r.data=r.data.slice(5);return r}var ea=class extends Gn{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",y.createLogger({id:"am"}));u(this,"denoiser");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,m;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),d=()=>{for(let p=0;p<s.length;p++){let _=URL.createObjectURL(new Blob(n[p])),I=document.createElement("a");I.href=_,I.download=`${s[p]}.pcm`,I.style.display="none",document.body.appendChild(I),I.click(),URL.revokeObjectURL(_),I.remove()}clearTimeout(a),o.abort("download")},c=Ro(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((I,A)=>n[A]=n[A]?n[A].concat(I[0]):[I[0]])}}),o).catch(_=>d));return{then:c.then.bind(c),download:d}}getPCM(e){var n;if(E(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}let t=new Float32Array(1920),s=0,o=new AbortController;return Ro([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(d){!d[0][0]||(t.set(d[0][0],s),s+=d[0][0].length,s>=1920&&(s=0,e(t),t=new Float32Array(1920)))}}),o).catch(d=>this.log.error(`stop getPCM reason:${d}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Kt)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof Ue)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ci)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Kt?delete this._localScreenAudioTrack:e instanceof Ue?delete this._localAudioTrack:e instanceof Ci}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;if(delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e),this.mixChangedDebounce)return this.mixChangedDebounce}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}enableEncodeNTPToAudioFrame(){this.addEncodeProcessor({processor:hh,type:1})}disableEncodeNTPToAudioFrame(){this.removeEncodeProcessor({type:1})}enableDecodeNTPFromAudioFrame(){this.addDecodeProcessor({processor:mh,type:1})}disableDecodeNTPFromAudioFrame(){this.removeDecodeProcessor({type:1})}};var ta=class{constructor(i,e){this.frame=i;this.ntpTime=e}},ia=class{constructor(i){u(this,"log");u(this,"minDelay",0);u(this,"maxDelay",4e3);u(this,"targetDelay",0);u(this,"data",[]);u(this,"workerIntervalId",-1);u(this,"workerIntervalTime",0);u(this,"intervalTime",0);u(this,"onAudioFrame");u(this,"onNeedFlushAudioDecoder");this.log=i.createChild({id:"buf"}),this.log.info("created")}get outputNTP(){var i;return((i=this.data[0])==null?void 0:i.ntpTime)||0}get length(){return this.data.length===0?0:this.data.length===1?20:(this.data[this.data.length-1].frame.timestamp-this.data[0].frame.timestamp)/48e3*1e3}get isOrdered(){return this.data.every((i,e)=>e===0?!0:i.frame.timestamp>this.data[e-1].frame.timestamp)}startOutput(){this.workerIntervalId=Q.run("intervalInWorker",()=>{this.output(),this.workerIntervalTime&&Date.now()-this.workerIntervalTime>40&&this.log.warn(`worker interval delay ${Date.now()-this.workerIntervalTime}`),this.workerIntervalTime=Date.now()},{delay:20})}stopOutput(){Q.clearTask(this.workerIntervalId),this.workerIntervalId=-1}input(i){let e=this.data.length-1,t=!1;for(;e>=0;e--)if(i.frame.timestamp<this.data[e].frame.timestamp&&(e===0||i.frame.timestamp>this.data[e-1].frame.timestamp)){t=!0;break}t?(this.data.splice(e,0,i),this.isOrdered||this.log.warn("not ordered",this.data.map(s=>s.frame.timestamp/48))):this.data.push(i),this.length>=this.targetDelay&&this.workerIntervalId===-1&&this.startOutput()}output(i=!1){if(this.length<=this.minDelay||i&&this.length<=this.targetDelay)return;let e=this.data.shift();e&&this.onAudioFrame&&(this.intervalTime&&Date.now()-this.intervalTime>40&&this.log.warn("output delay",Date.now()-this.intervalTime,"buf len",this.length),this.intervalTime=Date.now(),this.onAudioFrame(e)),this.length>=this.targetDelay+200&&(this.log.warn(`output to targetDelay ${this.length} -> ${this.targetDelay}`),this.output(!0))}checkData(){if(this.length>this.targetDelay){let i=this.data.shift();if(i&&this.onAudioFrame)return this.onAudioFrame(i),this.checkData()}return Promise.resolve()}setTargetDelay(i){if(!(Math.abs(i-this.targetDelay)<=20)){if(i>this.maxDelay){this.log.warn(`cannot setTargetDelay ${i} over ${this.maxDelay}`);return}this.minDelay=Math.max(0,i-200),i>this.targetDelay&&this.stopOutput(),this.targetDelay=i,this.log.info("setTargetDelay",i)}}destroy(){this.log.warn("destroy"),this.data=[],delete this.onAudioFrame,Q.clearTask(this.workerIntervalId)}};function ra(r=30,i=2){return j((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let d=new b({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});y.warn(d),i===2?n(d):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var ud=class extends mr{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ud.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},ut=ud;u(ut,"STATE_SUBSCRIBE","subscribe"),N([ra(5,1)],ut.prototype,"waitHasMediaTrack",1),N([he(H.INIT,ut.STATE_SUBSCRIBE,{success(){var i,e;this.log.info("subscribed"),T.emit(g.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!((((e=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:e.downlinkNetworkQuality)||0)>3)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var s,o;if(!((((o=(s=this.room)==null?void 0:s.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let n=this.kind===h.AUDIO,a=this.player.isPlaying||(n?this.getAudioLevel()>0:this.stat.framesDecoded>0);v[a?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),a||(v.addEnum({key:n?504701:514703,value:Xs()}),Z.uploadEvent({log:`stat-decode-failed-${this.kind}-${nr()||hi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`))}},5e3))},ignoreError:!0}),Qe(521716,!1)],ut.prototype,"subscribe",1),N([he(ut.STATE_SUBSCRIBE,H.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(g.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],ut.prototype,"unsubscribe",1);var Ci=class extends ut{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"p2pDelay",0);u(this,"currentAudioFrameNTPTime",-1);u(this,"prevWriteTime",0);u(this,"prevSendDecoderTime",0);u(this,"prevSendDecoderFrameNTP",0);u(this,"prevReceiveAudioFrameTime",0);u(this,"prevReceiveAudioFrameTimestamp",0);u(this,"audioDecoder");u(this,"trackGenerator");u(this,"remoteAudioFrameBuffer");this.manager=e.audioManager,this.initAudioDecoder()}initAudioDecoder(){if(this.audioDecoder||!this.room.enableChorus)return;this.trackGenerator=new MediaStreamTrackGenerator({kind:"audio"});let e=this.trackGenerator.writable.getWriter(),t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{e.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get outMediaTrack(){return this.trackGenerator&&this.room.role==="audience"?this.trackGenerator:this._outputTrack||null}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(s=>s)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&xn().AudioDecoder&&Dt:!1}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce((s,o,n)=>{if(o){let a={frame:s};return n===1&&this.hasFlag&&this.isSubscribed&&this.room.role==="audience"&&(a.onAudioFrameNTPTime=(d,c)=>{this.currentAudioFrameNTPTime=d,this.p2pDelay=_i($e())-d,this.p2pDelay<0;let l=c.timestamp,m=Date.now();this.prevReceiveAudioFrameTimestamp&&l-this.prevReceiveAudioFrameTimestamp>=60*48&&this.log.debug(`receive audio frame delta ${m-this.prevReceiveAudioFrameTime} timestamp delta ${(l-this.prevReceiveAudioFrameTimestamp)/48} bytes ${c.data.byteLength}`),this.prevReceiveAudioFrameTime=m,this.prevReceiveAudioFrameTimestamp=l;let p=$e()-this.p2pDelay;this.remoteAudioFrameBuffer||(this.remoteAudioFrameBuffer=new ia(this.log),this.remoteAudioFrameBuffer.setTargetDelay(300),this.remoteAudioFrameBuffer.onAudioFrame=_=>{var I,A;if(((I=this.audioDecoder)==null?void 0:I.state)==="configured"){this.audioDecoder.decode(_.frame);let R=_.frame.timestamp/48;this.prevSendDecoderTime&&R-this.prevSendDecoderTime>=60&&this.log.warn(`decoder input ntp delta ${R-this.prevSendDecoderTime} buffer len ${(A=this.remoteAudioFrameBuffer)==null?void 0:A.length}`),this.prevSendDecoderTime=R}}),this.remoteAudioFrameBuffer.input(new ta(new EncodedAudioChunk({data:c.data,timestamp:c.timestamp,type:"key"}),p)),c.data=new ArrayBuffer(0)},a.onAudioLeaving=()=>{this.log.warn("onAudioLeaving")}),o(a)}return s},e):e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}onFlagChanged(){super.onFlagChanged(),this.hasFlag||(this.clearBuffer(),this.currentAudioFrameNTPTime=-1)}unsubscribe(){super.unsubscribe(),this.clearBuffer()}clearBuffer(){this.remoteAudioFrameBuffer&&(this.remoteAudioFrameBuffer.destroy(),delete this.remoteAudioFrameBuffer,this.prevWriteTime=0,this.prevSendDecoderTime=0,this.prevSendDecoderFrameNTP=0,this.prevReceiveAudioFrameTime=0,this.prevReceiveAudioFrameTimestamp=0)}close(){super.close(),this.clearBuffer()}};var t_=[-1,-1,1,-1,-1,1,1,1],i_=[0,0,1,0,0,1,1,1];var ot=class extends H{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(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){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(i_),this.positionBuffer=this.createBuffer(t_),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${s.message||s}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Oe&&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){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 Oe){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:d}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:c,fps:l,name:a,cost:d},D({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};N([he(H.INIT,"connected",{sync:!0})],ot.prototype,"connect",1),N([he("connected",H.INIT,{ignoreError:!0,sync:!0})],ot.prototype,"disconnect",1),N([he([],"closed",{sync:!0})],ot.prototype,"close",1);function oe(...r){}var r_=r=>r();function md(){this.dispose()}var s_=()=>typeof __FASTRX_DEVTOOLS__!="undefined",o_=1,Zt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new hd(i,this,this.streamId++);return Ee.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ss=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=oe,this.error=oe,this.next=oe,this.dispose=oe,this.subscribe=oe,this.doDefer()}subscribe(i){return i instanceof Zt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(r_),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}},G=class extends ss{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)}},sa=class extends ss{constructor(i,e=oe,t=oe,s=oe){if(super(),this._next=e,this._error=t,this._complete=s,this.then=oe,i instanceof Zt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ee.defer(o,0)}),Ee.create(o),Ee.pipe(o),this.sourceId=o.id,this.subscribe(i),Ee.subscribe({id:o.id,end:!0}),e==oe?this._next=n=>Ee.next(o,0,n):this.next=n=>{Ee.next(o,0,n),e(n)},s==oe?this._complete=()=>Ee.complete(o,0):this.complete=()=>{this.dispose(),Ee.complete(o,0),s()},t==oe?this._error=n=>Ee.complete(o,0,n):this.error=n=>{this.dispose(),Ee.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function yi(r,...i){return i.reduce((e,t)=>t(e),r)}function Ye(r,i,e){if(s_()){let t=Object.defineProperties(Object.setPrototypeOf(r,Zt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Ee.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof Zt&&Ee.addSource(t,o)}return t}return r}function q(r,i){return function(...e){return t=>{if(t instanceof Zt){let s=Ye(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,Ee.pipe(s),s}else return s=>t(new r(s,...e))}}}function Xi(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var hd=class extends G{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ee.defer(this.source,this.id)})}next(i){Ee.next(this.source,this.id,i),this.sink.next(i)}complete(){Ee.complete(this.source,this.id),this.sink.complete()}error(i){Ee.complete(this.source,this.id,i),this.sink.error(i)}},Ee={addSource(r,i){Xi("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Xi("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Xi("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Xi("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Xi("defer",{id:r.id,streamId:i})},pipe(r){Xi("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Xi("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=o_++),Xi("create",{name:r.toString(),id:r.id})}},oa=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var pd=class extends ss{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 na(){return r=>{let i=new pd(r);if(r instanceof Zt){let e=Ye(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Ee.pipe(e),e}return Ye(i.add.bind(i),"share",arguments)}}function n_(...r){return Ye(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(d,c)=>{let l=new G(i);l.next=m=>{--t===0?(l.next=p=>{o[c]=p,i.next(o)},l.next(m)):o[c]=m},l.complete=n,l.subscribe(d)};r.forEach(a)},"combineLatest",arguments)}function ph(...r){return i=>Ye((e,t=0,s=r.length)=>{for(;t<s&&!e.disposed;)e.next(r[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var fd=class extends G{constructor(i,...e){super(i);let t=new G(this.sink);t.next=s=>this.buffer=s,t.complete=oe,t.subscribe(n_(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},eC=q(fd,"withLatestFrom"),_d=class extends G{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()}},tC=q(_d,"bufferCount"),gd=class extends G{constructor(i,e){super(i),this.buffer=[];let t=new G(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=oe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},iC=q(gd,"buffer");function Co(r){let i=arguments,e=na()(Ye(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=oe,e.complete=oe,e.error=oe,e}function fh(r){return Ye(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Ed(r,i){return e=>{let t=s=>e.next(s);e.defer(()=>i(t)),r(t)}}function ei(r,i){if("on"in r&&"off"in r)return Ye(Ed(e=>r.on(i,e),e=>r.off(i,e)),"fromEvent",arguments);if("addListener"in r&&"removeListener"in r)return Ye(Ed(e=>r.addListener(i,e),e=>r.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in r)return Ye(Ed(e=>r.addEventListener(i,e),e=>r.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function _h(){return Ye(r=>r.complete(),"empty",arguments)}var Td=class extends G{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},a_=q(Td,"reduce");var Sd=class extends G{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Ud=q(Sd,"filter"),Id=class extends G{next(i){}},mC=q(Id,"ignoreElements"),Ad=class extends G{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},gh=q(Ad,"take"),Rd=class extends G{constructor(i,e){super(i);let t=new G(i);t.next=()=>i.complete(),t.complete=md,t.subscribe(e)}},os=q(Rd,"takeUntil"),Cd=class extends G{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},c_=q(Cd,"takeWhile");var yd=class extends G{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},pC=q(yd,"skip"),bd=class extends G{constructor(i,e){super(i),i.next=oe;let t=new G(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=md,t.subscribe(e)}},fC=q(bd,"skipUntil"),Nd=class extends G{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Eh=q(Nd,"skipWhile"),d_={leading:!0,trailing:!1},vd=class extends G{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)}},Dd=class extends G{constructor(i,e,t=d_){super(i),this.durationSelector=e,this.config=t,this._throttle=new vd(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=oe,this._throttle.complete(),super.complete()}},_C=q(Dd,"throttle");var Od=class extends G{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Md=class extends G{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Od(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()}},gC=q(Md,"debounce");var kd=class extends G{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},EC=q(kd,"elementAt");var Pd=class extends G{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},TC=q(Pd,"findIndex"),Ld=class extends G{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},SC=q(Ld,"first"),wd=class extends G{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()}},IC=q(wd,"last"),xd=class extends G{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},AC=q(xd,"every");var Vd=class extends G{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},bC=q(Vd,"scan"),Bd=class extends G{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},NC=q(Bd,"pairwise"),Fd=class extends G{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Th=q(Fd,"map");var ns=class extends G{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()}},as=class extends G{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},aa=class extends ns{},ca=class extends as{next(i){this.subInner(i,aa),this.next=e=>{this.currentSink.dispose(),this.subInner(e,aa)}}},Qd=q(ca,"switchMap");function ha(r){return(i,e)=>r(()=>i,e)}var Sh=ha(q(ca,"switchMapTo")),$d=class extends ns{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},da=class extends as{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(),$d),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},vC=q(da,"concatMap"),DC=ha(q(da,"concatMapTo")),Hd=class extends ns{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},ua=class extends as{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Hd),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},OC=q(ua,"mergeMap"),MC=ha(q(ua,"mergeMapTo")),Gd=class extends ns{dispose(){this.context.resetNext(),super.dispose()}},la=class extends as{next(i){this.next=oe,this.subInner(i,Gd)}},kC=q(la,"exhaustMap"),PC=ha(q(la,"exhaustMapTo")),Wd=class extends G{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=Co(),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)}},LC=q(Wd,"groupBy"),Jd=class extends G{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}},wC=q(Jd,"timeInterval"),jd=class extends G{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()}},xC=q(jd,"bufferTime"),qd=class extends G{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},UC=q(qd,"delay"),Xd=class extends G{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},VC=q(Xd,"catchError");var pr=(r=oe,i=oe,e=oe)=>t=>new sa(t,r,i,e),zd=class extends G{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)}))}},$C=q(zd,"tap"),Yd=class extends G{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new oa(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},HC=q(Yd,"timeout");var u_=yi(fh(250),Th(()=>performance.now()),na());var Ih=r=>i=>{let e=performance.now();yi(u_,Eh(t=>t-e<r),gh(1))(i)};var h_=[0,1,1,1,0,0,1,0],yo=class extends ot{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof ze?this.ctx2d=e.ctx||null:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(h_)}start(e){this.log.info(`${this.name} start render ${e} fps`),Q.clearTask(this._intervalId),this._intervalId=Q.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Q.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Oe){let s=this.context.ctx.getError();s&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e){if(this._intervalId&&(Q.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Q.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),Q.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},cs=class extends yo{constructor(e,t){super(e,t);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",ei(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(Vi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ei(this._videoTrack,"mute"),yi(ei(this._videoTrack,"ended"),os(this._closedOb),pr(()=>{this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=yi(this._muteOb,os(this._closedOb),Sh(Ih(5e3)),pr(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},ma=class extends cs{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var pa=class extends cs{constructor(e,t,s){super(e,{name:"smallDestination",logger:s});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var bo=class extends ot{constructor(e,t){super(e,D({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,di===16&&(this._canvasRendered=Co(),yi(this._canvasRendered,ph(this._image),Qd(s=>s instanceof HTMLCanvasElement?ei(s,"rendered"):_h()),os(ei(this,"closed")),pr(()=>{this.update(0)})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),lo()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,s)=>{document.hidden||(this._totalFrames=s.presentedFrames,this.update(1))}))}_render(e,t){let{width:s,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{videoWidth:s,videoHeight:o}=n,!s||!o)return!1;n.width=s,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:s,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(s===this.width&&o===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&({width:s,height:o}=n,this._lastImage=n);if(!this._autoResize)return!0;if(this.width===s&&this.height===o&&this.totalFrames){if(t){this.useTexture();let a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,n)}this.resize(s,o)}return!0}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)}},No=class extends bo{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource",yi(ei(this._player,Ae.PLAYER_STATE_CHANGED),os(ei(this,"closed")),Ud(({state:o})=>o==="PLAYING"),pr(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},bi=class extends No{constructor(i,e,t){super(i,new tt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var p_=`
|
|
32
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Kc,r.innerText=`${Ut()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${$n}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){td()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Zr}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",y.info("show autoplay dialog"),K.uploadEvent({log:Pf}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){y.warn("confirm clicked, try resume stream"),T.emit(E.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Jl}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||K.uploadEvent({log:Lf}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ql,"_blank"),this._isQuestionClicked||K.uploadEvent({log:xf}),this._isQuestionClicked=!0}},Hn=Zc;var et=class extends qt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,g(e.viewMirror)||(this.viewMirror=e.viewMirror),g(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var r;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this._pausedRetryCount>0&&!td()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let o=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=o.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!o.includes("scaleX")&&(this.element.style.transform=`${o} scaleX(-1)`)}}setCanvas(e){var t,r;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((r=this.container)==null||r.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Re.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};function dr(s,i){return f(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),y.info("worklet addModule success")}catch(e){throw y.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var ur=new window.AudioContext({sampleRate:48e3}),es=()=>{ur.state==="suspended"?(ur.resume(),document.addEventListener("click",es)):ur.state==="interrupted"?ur.resume():document.removeEventListener("click",es)};document.addEventListener("click",es);ur.onstatechange=()=>{y.info(`context state: ${ur.state}`),es()};var ve=s=>ur;var dt=class{constructor(){this.pre=new Set;this.next=new Set;this.connectedNodes=new Set;this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.node&&(this.node.channelCount=i),this.next.forEach(e=>e.channelCount=i)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(t){y.error(t),v.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){y.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},Gn=class extends dt{constructor(e=256){super();this.fftSize=e;this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},So=class{constructor(){this.source=new dt;this.gain=new dt;this.destination=new dt}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(id(i))}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ts=class extends So{constructor(e){super();this.context=e;this.denoiser=new dt;this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},Wn=class{constructor(){this.audioContext=ve("audio-mixer");this.destination=this.audioContext.createMediaStreamDestination();this.inputs=new Set;this.mixWeight=0}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zl=new WeakMap;function id(s){let i=zl.get(s);if(i)return i;let e=ve();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return zl.set(s,i),i}window.AudioWorkletProcessor||(window.AudioWorkletProcessor=class{constructor(){u(this,"port")}});var rd=class 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=i=>{let{data:e}=i;switch(e.name){case"chunk":this.cache.push.apply(this.cache,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;break}}}process(i,e){let t=i[0],r=e[0];if(!t&&!r)return!0;if(this.isStop)return!1;let o=r&&r[0]?r[0].length:0,n=this.cache.length;n>o?(r[0].set(this.cache.slice(0,o)),this.cache=this.cache.slice(o)):this.unmute&&r[0].set(t[0]);let a=n>o?r[0]:t[0];if(!a)return!0;let c=0;for(let l=0;l<a.length;++l)c=Math.max(Math.abs(a[l]),c);let d=a.reduce((l,m)=>l+m*m,0)/a.length;return this.volume=c,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(d)+100,0)/100,cacheLen:n,outputLen:o})),!0}},sd=rd.toString();delete window.AudioWorkletProcessor;var Xt=class{constructor(i){this._volume=0;this._volumeDb=0;this._scriptProcessorNode=null;this._audioWorkletNode=null;this._interval=200;this.ready=this.preload();let{log:e}=i;this._log=e,T.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Xt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Xt.workletReady){let i=`${sd.slice(0,5)} VolumeMeterWorklet ${sd.slice(6)};registerProcessor('volume-meter', VolumeMeterWorklet);`;Xt.workletReady=dr(Xt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Xt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Xt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Xt.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}`),K.logFailedEvent({userId:this._log.userId,eventType:Ge.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=ve("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Xt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(E.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})}},is=Xt;is.lastMessageTime=0,is.audioContext=ve("volume-meter");var Jn=class extends dt{constructor(e){super();this._volumeMeter=new is(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()}}},lr=is;var eh=ye(xe(),1);var Kl=s=>i=>i.deviceId===s;var Io=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&rs(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Kl(r.deviceId))){let o=`${this.kind}${this.type}Added`;y.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Kl(r.deviceId))){let o=`${this.kind}${this.type}Removed`;y.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},od=class extends eh.EventEmitter{constructor(){super();u(this,"audioInputs",new Io(h.AUDIO));u(this,"videoInputs",new Io(h.VIDEO));u(this,"audioOutputs",new Io(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(tr,()=>{this.update()},{delay:1e4}))}init(){jn().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 jn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=ve())==null?void 0:t.outputLatency)>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(o=>r.label.toLowerCase().includes(o)))}},ge=Ns||Dr?null:new od;function rs(s){return s.deviceId===s.groupId&&s.groupId===""}function jn(){return f(this,arguments,function*(s=0){if(Ei()||!Ln())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{rs(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(r){y.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&&nd.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function qe(s=!1){return ge.update(s?1:0).then(i=>i.audioInputs.devices)}function tt(s=!1){return ge.update(s?2:0).then(i=>i.videoInputs.devices)}var Zl=!1;function th(){return f(this,null,function*(){try{Zl||(Zl=!0,y.info(`speakers:${(yield Wi()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function Wi(s=!1){return f(this,null,function*(){return ge.update(s?1:0).then(i=>i.audioOutputs.devices)})}var nd=new Set;function ih(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!nd.has(t)}function rh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!nd.has(t)}function ad(s,i){return f(this,null,function*(){let t=(yield qe()).find(r=>r.deviceId===er);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function sh(o){return f(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===h.AUDIO&&s===er?yield ad(e,t):!0})}var qn,cd=class extends So{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new Gn);this.volumeMeter=new Jn({log:this.log}),this.volumeDestination=new dt,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Ji=class extends qt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",ve("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");e.url&&(this.url=e.url),this.pipeline=new cd(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(){if((Ui==="15.2"||Ui==="15.3"||Ui==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=qn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.url&&(t.crossOrigin="anonymous",t.src=this.url),t.ontimeupdate=()=>{this.emit(Re.TIME_UPDATED,this.currentTime)},this.element=t,t===qn&&(qn=void 0),this.bindElementEvents()}play(){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(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(ve("player").createAnalyser()),this.setVolume(this._volume),th(),Se(Ji.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),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()}},Xn=class extends Ji{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Re.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}},Qn=class extends Ji{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new dt);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this._output.setNode(ve("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Re.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Ee(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&Wr&&(qn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var hr=class extends H{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?Qn:et}){var a;super();u(this,"id",so());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");this.userId=e||"",this.mediaType=r,this._log=y.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof it?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof it}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Re.PLAYER_STATE_CHANGED,c=>{T.emit(E.PLAYER_STATE_CHANGED,D({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(Re.LOADED_DATA,()=>{T.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Re.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Re.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||y}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=_e(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!g(t.muted)&&this.setPlayerMute(t.muted),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof et&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),_e(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!g(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof et&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof et&&this.player.setContainer(r)),T.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),_e(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(le(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new et({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Nt(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),T.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Ue(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Ee(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(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Nt(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Hn;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof et?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};N([he([],H.INIT,{sync:!0})],hr.prototype,"close",1);var Uf=Object.prototype.hasOwnProperty,{toString:XS}=Object.prototype;function Vf(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Ze(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(Uf.call(s,i))return!1;return!0}}return!1}var Qt=Vf;var Bf=function(s){return f(this,null,function*(){let i=Ff(s);y.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId"];i.audio&&(e=yield qe(),y.info(`microphones: ${bt(e,{keysToInclude:r})}`)),i.video&&(t=yield tt(),y.info(`cameras: ${bt(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return qc&&o.getTracks().forEach(n=>{y.info(`${n.kind} capabilities: ${bt(n.getCapabilities(),{keysToInclude:rn})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=U({key:w.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=U({key:w.MICROPHONE_NOT_FOUND}))),new b({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},$f=Bt({retryFunction:Bf,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!Je||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&oh(t[0].microphoneId,!1),t[0].cameraId&&oh(t[0].cameraId,!0)},onRetrying:s=>{y.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{K.logFailedEvent({eventType:Ge.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{K.logSuccessEvent({eventType:Ge.GET_USER_MEDIA_RETRY}),K.uploadEvent({log:`stat-${Ge.GET_USER_MEDIA_RETRY}-success-${s}`})}});function oh(s,i){return f(this,null,function*(){let t=(i?yield tt():yield qe()).find(r=>r.deviceId===s);t&&ie(t.getCapabilities)&&y.warn(bt(t.getCapabilities(),{keysToInclude:rn}))})}function Ff(s){return{audio:Hf(s),video:Gf(s)}}function Hf(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!Qt(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(ee(s.channelCount)&&(i.channelCount=s.channelCount),le(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),le(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),le(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),Qt(i)?!0:i)}function Gf(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!Qt(e)?e:(s.width&&(e.width={ideal:s.width},i&&!se&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!se&&(e.height.max=s.height)),se&&At&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),Qt(e)?!0:e)}var nh=$f;function zn(s){return j((i,e)=>function(...t){return f(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Dt(s){return j((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function j(s){return function(i,e,t){return t.value=s(t.value,e),t}}var ah=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&y.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{y.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var Wf=0,Yn=class{constructor(){this.log=y.createLogger({id:`fq${++Wf}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=D({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Ao=new WeakMap,Kn=new WeakMap;function zt(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=Ao.get(this)||new Yn;return Ao.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function ch(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=Ao.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(m=>{o.find(p=>p===m)||(l=!1)}),l?(c.reject(new b({code:S.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function Zn(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=Ao.get(this))==null?void 0:a.queue)==null||c.forEach(l=>n.push(l)),(d=Kn.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(m=>n.push(m))),n.forEach(l=>{l.reject(new b({code:S.API_CALL_ABORTED,message:s}))}),Ao.delete(this),Kn.delete(this),r.apply(this,o)},t}}function Ti(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Kn.get(this)||new Map,c=a.get(o(n))||new Yn;return a.set(o(n),c),Kn.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Xe(s,i){return j((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=P();return or(n)?n.then(c=>(i?v.addSuccessEvent({key:o,cost:P()-a}):v.addSuccessEvent({key:o}),c)).catch(c=>{throw v.addFailedEvent({key:o,error:c}),c}):(v.addSuccessEvent({key:o}),n)}catch(n){throw v.addFailedEvent({key:o,error:n}),n}})}var dd=class extends hr{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Ue(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Ee(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let r=P();T.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield nh(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:P()-r}),o}catch(r){throw T.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===H.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&Gt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield sh({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),jn().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!rh(this.mediaTrack)||this.kind===h.VIDEO&&!ih(this.mediaTrack)||this._isRecapturing||e&&At&&Je)}onTrackMuted(){if(super.onTrackMuted(),ah(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<kr){setTimeout(()=>this.onTrackMuted(),kr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((We||fe)&&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(Se(dd.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<kr){setTimeout(()=>this.onTrackEnded(),kr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield qe():yield tt()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof me;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Co.get(t)||0)+1;if(Co.set(t,r),r>=3){let o=e?(yield tt()).find(n=>!Co.has(n.deviceId)):(yield qe()).find(n=>!Co.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},it=dd;N([he(H.INIT,"capture",{ignoreError:!0,sync:!0})],it.prototype,"setStateToCapture",1),N([zt()],it.prototype,"capture",1),N([he("capture","publish",{ignoreError:!0,success(){var i,e;this.room.localTracks.add(this),T.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((e=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:e.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var r,o;if(!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let n=this.kind===h.AUDIO,a=this.stat.bytesSent>0;v[a?"addSuccessEvent":"addFailedEvent"]({key:n?503700:513702}),a||(v.addEnum({key:n?503701:513703,value:Qs()}),K.uploadEvent({log:`stat-encode-failed-${this.kind}-${sr()||li()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(s){let i="error",e=s.cause;e.message.includes("timeout")?i="timeout":e.code===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}}),Xe(521714,!1)],it.prototype,"publish",1),N([j(s=>function(){return f(this,null,function*(){let i=this.state==="publish"?"started":"starting";s.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),he([],"capture",{sync:!0})],it.prototype,"unpublish",1);var Co=new Map;T.on(E.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&Co.delete(s.track.deviceId)});var Me=class extends it{constructor(e){super(1,Xn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"codecPipeline",[]);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new ts(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get volumeDb(){return lr.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}get playerMediaTrack(){return this.mediaTrack}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:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield Se(Me.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(o){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0}){let n=yield Se(Me.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,customSource:t});return es(),n})}switchDevice(e){return f(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===er){if(yield ad(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),this.room&&(yield this.room.replaceTrack(this)),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ge&&!ge.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ge.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),de(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield qe();t[0]?this.recapture(t[0].deviceId):ge.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=!1;return!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!g(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId)),n})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(r=>this._log.warn(`${e?"enable":"disable"} ANS failed `,r))}addDenoiser(e){var t;if(Rt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),ge.off("audioInputAdded",this.handleMicrophoneAdded,this),ge.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Se(Me.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield qe()).find(o=>o.deviceId!==e);if(r)yield Se(Me.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce((t,r)=>r?r({frame:t,ntp:ot()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Ii=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var ea=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ii(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let r=this.getNaluCount(i.data),o=9-r;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),m=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)d.setInt8(m++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,l.getInt8(p));return i.data=c,n.length}return 0}};var me=class extends it{constructor(e,t=4){super(t,et);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new ea);this.manager=e;let r=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(x(D({},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(!(!Gt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,r,o;if(Y(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Se(me.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Se(me.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=D({},e),r=t.width>t.height;t.width*t.height<=160*120&&fe&&Ct&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Ic&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(x(D({},this.profile),{width:1920,height:1080})))}applyProfile(){var r;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(r=this.mediaTrack)==null?void 0:r.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Gt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Oc()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ge&&!ge.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ge.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),de(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield tt();t[0]?this.recapture(t[0].deviceId):ge.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduce((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return f(this,null,function*(){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),Se(me.prototype,this,"play").call(this,e,t)})}close(){ge.off("videoInputAdded",this.handleCameraAdded,this),ge.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Se(me.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield tt()).find(o=>o.deviceId!==e);if(r)yield Se(me.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}};var uh=so();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:uh,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var Xf=function(s){return f(this,null,function*(){let i=null,e=Yf(s);y.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(Gr&&Rt<74||Je||se)&&y.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){y.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield Qf(r,s.captureElement))}if(s.audio){let o=zf(s);y.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function Qf(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ie(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===uh))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){y.warn(`cropTo target failed ${t}`)}})}function zf(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return g(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function Yf(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Je?{max:s.width}:{ideal:s.width,max:s.width},height:Je?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var lh=Xf;var rt=class extends me{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):m=yield lh({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof b?m:new b({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};var Yt=class extends Me{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Kf="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",ud;function Ro(s){return f(this,null,function*(){let i=ve("dump");ud||(ud=dr(i,URL.createObjectURL(new Blob([Kf],{type:"application/javascript"})))),yield ud;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:s.length,numberOfOutputs:0});return s.forEach((t,r)=>t.connect(e,0,r)),new ReadableStream({start(t){e.port.onmessage=r=>{t.enqueue(r.data)}},cancel(){s.forEach(t=>t.disconnect(e)),e.port.close()}})})}var ta=class extends Wn{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",y.createLogger({id:"am"}));u(this,"denoiser");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,m;if(!this._localAudioTrack)return;let t=[],r=[];(l=this._localAudioPipline)!=null&&l.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 o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<r.length;p++){let _=URL.createObjectURL(new Blob(n[p])),I=document.createElement("a");I.href=_,I.download=`${r[p]}.pcm`,I.style.display="none",document.body.appendChild(I),I.click(),URL.revokeObjectURL(_),I.remove()}clearTimeout(a),o.abort("download")},d=Ro(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((I,A)=>n[A]=n[A]?n[A].concat(I[0]):[I[0]])}}),o).catch(_=>c));return{then:d.then.bind(d),download:c}}getPCM(e){var n;if(g(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let t=new Float32Array(1920),r=0,o=new AbortController;return Ro([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){!c[0][0]||(t.set(c[0][0],r),r+=c[0][0].length,r>=1920&&(r=0,e(t),t=new Float32Array(1920)))}}),o).catch(c=>this.log.warn(`stop getPCM reason:${c}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Yt)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof Me)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ai)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Yt?delete this._localScreenAudioTrack:e instanceof Me?delete this._localAudioTrack:e instanceof Ai}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;if(delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e),this.mixChangedDebounce)return this.mixChangedDebounce}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function ia(s=30,i=2){return j((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});y.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var ld=class extends hr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ld.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag),this.emit("flag-changed",this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},ut=ld;u(ut,"STATE_SUBSCRIBE","subscribe"),N([ia(5,1)],ut.prototype,"waitHasMediaTrack",1),N([he(H.INIT,ut.STATE_SUBSCRIBE,{success(){var i,e;this.log.info("subscribed"),T.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!((((e=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:e.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var r,o;if(!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let n=this.kind===h.AUDIO,a=this.player.isPlaying||(n?this.getAudioLevel()>0:this.stat.framesDecoded>0);v[a?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),a||(v.addEnum({key:n?504701:514703,value:Qs()}),K.uploadEvent({log:`stat-decode-failed-${this.kind}-${sr()||li()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`))}},5e3))},ignoreError:!0}),Xe(521716,!1)],ut.prototype,"subscribe",1),N([he(ut.STATE_SUBSCRIBE,H.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],ut.prototype,"unsubscribe",1);var Ai=class extends ut{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"audioDecoder");u(this,"trackGenerator");this.manager=e.audioManager}get volumeDb(){return lr.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}initTrackGenerator(){!this.room.enableChorus||this.trackGenerator||(this.log.info("initTrackGenerator"),this.trackGenerator=new MediaStreamTrackGenerator({kind:"audio"}),this.player.setTrack(this.outMediaTrack),this.player.isPlaying||this.player.play().catch(e=>this._log.error(e)))}deleteTrackGenerator(){this.trackGenerator&&(this.log.info("deleteTrackGenerator"),this.trackGenerator.stop(),delete this.trackGenerator,this.player.setTrack(this.outMediaTrack))}initAudioDecoder(){if(this.audioDecoder||!this.room.enableChorus)return;this.trackGenerator=new MediaStreamTrackGenerator({kind:"audio"});let e=this.trackGenerator.writable.getWriter(),t=new AudioDecoder({error:r=>this._log.error(r),output:r=>{e.write(r)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:2}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get outMediaTrack(){return this.trackGenerator&&this.room.role==="audience"?this.trackGenerator:this._outputTrack||null}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&&Vn().AudioDecoder&&vt:!1}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce((r,o,n)=>{if(o){let a={frame:r};return n===1&&this.hasFlag&&this.isSubscribed&&this.room.role==="audience"&&(a.onAudioFrameNTPTime=({ntp:c,frame:d,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:c,frame:d,hasLeavingTag:l})}),o(a)}return r},e):e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var e_=[-1,-1,1,-1,-1,1,1,1],t_=[0,0,1,0,0,1,1,1];var st=class extends H{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(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 Qe){if(e.ctx&&t.create2d){let r=document.createElement("canvas"),o=typeof r.transferControlToOffscreen=="function"?r.transferControlToOffscreen():r;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(t_),this.positionBuffer=this.createBuffer(e_),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof ke&&this.render(e)||this.context instanceof Qe&&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){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 ke){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):this.ctx2d.drawImage(e,t,r,o,n),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:d,fps:l,name:a,cost:c},D({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.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};N([he(H.INIT,"connected",{sync:!0})],st.prototype,"connect",1),N([he("connected",H.INIT,{ignoreError:!0,sync:!0})],st.prototype,"disconnect",1),N([he([],"closed",{sync:!0})],st.prototype,"close",1);function oe(...s){}var i_=s=>s();function pd(){this.dispose()}var r_=()=>typeof __FASTRX_DEVTOOLS__!="undefined",s_=1,Kt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new md(i,this,this.streamId++);return Te.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ss=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=oe,this.error=oe,this.next=oe,this.dispose=oe,this.subscribe=oe,this.doDefer()}subscribe(i){return i instanceof Kt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(i_),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}},G=class extends ss{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)}},ra=class extends ss{constructor(i,e=oe,t=oe,r=oe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=oe,i instanceof Kt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Te.defer(o,0)}),Te.create(o),Te.pipe(o),this.sourceId=o.id,this.subscribe(i),Te.subscribe({id:o.id,end:!0}),e==oe?this._next=n=>Te.next(o,0,n):this.next=n=>{Te.next(o,0,n),e(n)},r==oe?this._complete=()=>Te.complete(o,0):this.complete=()=>{this.dispose(),Te.complete(o,0),r()},t==oe?this._error=n=>Te.complete(o,0,n):this.error=n=>{this.dispose(),Te.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function Ci(s,...i){return i.reduce((e,t)=>t(e),s)}function ze(s,i,e){if(r_()){let t=Object.defineProperties(Object.setPrototypeOf(s,Kt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Te.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof Kt&&Te.addSource(t,o)}return t}return s}function q(s,i){return function(...e){return t=>{if(t instanceof Kt){let r=ze(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Te.pipe(r),r}else return r=>t(new s(r,...e))}}}function ji(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var md=class extends G{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Te.defer(this.source,this.id)})}next(i){Te.next(this.source,this.id,i),this.sink.next(i)}complete(){Te.complete(this.source,this.id),this.sink.complete()}error(i){Te.complete(this.source,this.id,i),this.sink.error(i)}},Te={addSource(s,i){ji("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){ji("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){ji("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){ji("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){ji("defer",{id:s.id,streamId:i})},pipe(s){ji("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){ji("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=s_++),ji("create",{name:s.toString(),id:s.id})}},sa=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var fd=class extends ss{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 oa(){return s=>{let i=new fd(s);if(s instanceof Kt){let e=ze(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Te.pipe(e),e}return ze(i.add.bind(i),"share",arguments)}}function o_(...s){return ze(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,d)=>{let l=new G(i);l.next=m=>{--t===0?(l.next=p=>{o[d]=p,i.next(o)},l.next(m)):o[d]=m},l.complete=n,l.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function hh(...s){return i=>ze((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var _d=class extends G{constructor(i,...e){super(i);let t=new G(this.sink);t.next=r=>this.buffer=r,t.complete=oe,t.subscribe(o_(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},zC=q(_d,"withLatestFrom"),Ed=class extends G{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()}},YC=q(Ed,"bufferCount"),gd=class extends G{constructor(i,e){super(i),this.buffer=[];let t=new G(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=oe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},KC=q(gd,"buffer");function yo(s){let i=arguments,e=oa()(ze(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=oe,e.complete=oe,e.error=oe,e}function mh(s){return ze(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Td(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function Zt(s,i){if("on"in s&&"off"in s)return ze(Td(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return ze(Td(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return ze(Td(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function ph(){return ze(s=>s.complete(),"empty",arguments)}var Sd=class extends G{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},n_=q(Sd,"reduce");var Id=class extends G{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Vd=q(Id,"filter"),Ad=class extends G{next(i){}},dR=q(Ad,"ignoreElements"),Cd=class extends G{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},fh=q(Cd,"take"),Rd=class extends G{constructor(i,e){super(i);let t=new G(i);t.next=()=>i.complete(),t.complete=pd,t.subscribe(e)}},os=q(Rd,"takeUntil"),yd=class extends G{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},a_=q(yd,"takeWhile");var bd=class extends G{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},uR=q(bd,"skip"),Nd=class extends G{constructor(i,e){super(i),i.next=oe;let t=new G(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=pd,t.subscribe(e)}},lR=q(Nd,"skipUntil"),vd=class extends G{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},_h=q(vd,"skipWhile"),c_={leading:!0,trailing:!1},Dd=class extends G{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)}},Od=class extends G{constructor(i,e,t=c_){super(i),this.durationSelector=e,this.config=t,this._throttle=new Dd(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=oe,this._throttle.complete(),super.complete()}},hR=q(Od,"throttle");var Md=class extends G{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},kd=class extends G{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Md(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()}},mR=q(kd,"debounce");var Pd=class extends G{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},pR=q(Pd,"elementAt");var Ld=class extends G{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},fR=q(Ld,"findIndex"),xd=class extends G{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},_R=q(xd,"first"),wd=class extends G{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()}},ER=q(wd,"last"),Ud=class extends G{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},gR=q(Ud,"every");var Bd=class extends G{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))}},AR=q(Bd,"scan"),$d=class extends G{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},CR=q($d,"pairwise"),Fd=class extends G{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Eh=q(Fd,"map");var ns=class extends G{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()}},as=class extends G{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},na=class extends ns{},aa=class extends as{next(i){this.subInner(i,na),this.next=e=>{this.currentSink.dispose(),this.subInner(e,na)}}},zd=q(aa,"switchMap");function la(s){return(i,e)=>s(()=>i,e)}var gh=la(q(aa,"switchMapTo")),Hd=class extends ns{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},ca=class extends as{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(),Hd),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},RR=q(ca,"concatMap"),yR=la(q(ca,"concatMapTo")),Gd=class extends ns{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},da=class extends as{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Gd),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},bR=q(da,"mergeMap"),NR=la(q(da,"mergeMapTo")),Wd=class extends ns{dispose(){this.context.resetNext(),super.dispose()}},ua=class extends as{next(i){this.next=oe,this.subInner(i,Wd)}},vR=q(ua,"exhaustMap"),DR=la(q(ua,"exhaustMapTo")),Jd=class extends G{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=yo(),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)}},OR=q(Jd,"groupBy"),jd=class extends G{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}},MR=q(jd,"timeInterval"),qd=class extends G{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()}},kR=q(qd,"bufferTime"),Xd=class extends G{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)}},PR=q(Xd,"delay"),Qd=class extends G{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},LR=q(Qd,"catchError");var mr=(s=oe,i=oe,e=oe)=>t=>new ra(t,s,i,e),Yd=class extends G{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)}))}},UR=q(Yd,"tap"),Kd=class extends G{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new sa(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},VR=q(Kd,"timeout");var d_=Ci(mh(250),Eh(()=>performance.now()),oa());var Th=s=>i=>{let e=performance.now();Ci(d_,_h(t=>t-e<s),fh(1))(i)};var l_=[0,1,1,1,0,0,1,0],bo=class extends st{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof Qe?this.ctx2d=e.ctx||null:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(l_)}start(e){this.log.info(`${this.name} start render ${e} fps`),Z.clearTask(this._intervalId),this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ke){let r=this.context.ctx.getError();r&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e){if(this._intervalId&&(Z.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),Z.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},cs=class extends bo{constructor(e,t){super(e,t);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",Zt(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(wi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Zt(this._videoTrack,"mute"),Ci(Zt(this._videoTrack,"ended"),os(this._closedOb),mr(()=>{this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=Ci(this._muteOb,os(this._closedOb),gh(Th(5e3)),mr(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},ha=class extends cs{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var ma=class extends cs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var No=class extends st{constructor(e,t){super(e,D({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,ci===16&&(this._canvasRendered=yo(),Ci(this._canvasRendered,hh(this._image),zd(r=>r instanceof HTMLCanvasElement?Zt(r,"rendered"):ph()),os(Zt(this,"closed")),mr(()=>{this.update(0)})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),ho()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&({width:r,height:o}=n,this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},vo=class extends No{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",Ci(Zt(this._player,Re.PLAYER_STATE_CHANGED),os(Zt(this,"closed")),Vd(({state:o})=>o==="PLAYING"),mr(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},Ri=class extends vo{constructor(i,e,t){super(i,new et({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var m_=`
|
|
33
33
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
34
34
|
attribute vec4 a_position;
|
|
35
35
|
attribute vec2 a_texCoord;
|
|
@@ -39,7 +39,7 @@ void main() {
|
|
|
39
39
|
gl_Position = a_position;
|
|
40
40
|
v_texCoord = a_texCoord;
|
|
41
41
|
}
|
|
42
|
-
`,
|
|
42
|
+
`,p_=`
|
|
43
43
|
// \u7247\u5143\u7740\u8272\u5668
|
|
44
44
|
precision mediump float;
|
|
45
45
|
varying vec2 v_texCoord;
|
|
@@ -47,26 +47,26 @@ uniform sampler2D u_texture;
|
|
|
47
47
|
|
|
48
48
|
void main() {
|
|
49
49
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
50
|
-
} `;var fr=class extends H{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");u(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new bi(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new cs(this,e)}createVideoImageSource(e,t){return new bo(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new No(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(fr,"_ids",0);var __={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Oe=class extends fr{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${fr._ids++}`),this.ctx=this._canvas.getContext("webgl2",__),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,p_),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,f_),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,o=s.createShader(e);return s.shaderSource(o,t),s.compileShader(o),o}createProgram(e,t){let s=this.ctx,o=s.createProgram();return s.attachShader(o,e),s.attachShader(o,t),s.linkProgram(o),s.getProgramParameter(o,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(o)),o}};N([he(H.INIT,"created",{sync:!0,fail(r){v.addFailedEvent({key:512700,error:r.cause})},success(){v.addSuccessEvent({key:512700})}})],Oe.prototype,"create",1),N([he("created",H.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],Oe.prototype,"destroy",1);var ze=class extends fr{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${fr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,v.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),v.addSuccessEvent({key:512703})}};N([he(H.INIT,"created",{sync:!0,fail(r){v.addFailedEvent({key:512701,error:r.cause})},success(){v.addSuccessEvent({key:512701})}})],ze.prototype,"create",1),N([he("created",H.INIT,{ignoreError:!0,sync:!0})],ze.prototype,"destroy",1);function g_(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var Mt=class extends ut{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}play(e,t){return(le(t==null?void 0:t.canvasRender)?t.canvasRender:di===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new ze({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let s=new yo(e,{name:"remotePlayer",logger:this.log});t.connect(s),this.player.setCanvas(e._canvas),lo()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,s=g_(t);if(!te(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(s===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${s} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${s}, current: ${e.frameRate}`),e.frameRate=s}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let s=e.find(a=>a.uint32_video_stream_type===t);return(s==null?void 0:s.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager?this.manager.decodePipeline.some(e=>e):!1}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce((t,s)=>s?s({frame:t,track:this}):t,e):e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},ds=class extends Mt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};var us=new Map;T.on(g.JOIN_SUCCESS,({room:r})=>{de(r.userId,{eventId:32788})});T.on(g.LEAVE_START,({room:r})=>{de(r.userId,{eventId:32789})});T.on(g.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),de(r.room.userId,{eventId:i})}});T.on(g.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),de(r.room.userId,{eventId:i})}});T.on(g.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?de(r.room.userId,{eventId:r.isRemote?32785:32772,remoteUserId:r.isRemote?r.userId:void 0}):de(r.room.userId,{eventId:r.isRemote?32784:32773,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(g.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?de(r.room.userId,{eventId:r.isRemote?32787:32774,remoteUserId:r.isRemote?r.userId:void 0}):de(r.room.userId,{eventId:r.isRemote?32786:32775,remoteUserId:r.isRemote?r.userId:void 0}))});T.on(g.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&de(r.room.userId,{eventId:32777,remoteUserId:r.userId}),r.mediaType===4&&de(r.room.userId,{eventId:32776,remoteUserId:r.userId}),r.mediaType===8&&de(r.room.userId,{eventId:32803,remoteUserId:r.userId}))});T.on(g.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&de(r.room.userId,{eventId:32779,remoteUserId:r.userId}),r.mediaType===4&&de(r.room.userId,{eventId:32778,remoteUserId:r.userId}),r.mediaType===8&&de(r.room.userId,{eventId:32804,remoteUserId:r.userId}))});T.on(g.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&de(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});T.on(g.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&de(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});T.on(g.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&de(r.userId,{eventId:t})});T.on(g.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=s?32801:32798:o=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799);break;case"RECONNECTING":o=s?32800:32797;break}o&&de(r.userId,{eventId:o,remoteUserId:t})});T.on(g.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:o})=>{let n=t?1:0;s||(n=t?3:2);let a=e==="h264"?0:2,d={eventId:4004,param1:n,param2:a,streamType:o||2};i&&(d.remoteUserId=i,d.eventId=4005),de(r,d),v.addEnum({key:i?514701:513701,value:n}),v.addEnum({key:i?514700:513700,value:a})});T.on(g.LOCAL_TRACK_RECAPTURE,({track:r,error:i})=>{if(r.userId){let e={eventId:2003,param1:0};r.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=r.streamType==="auxiliary"?7:2,i&&(e.param1=8)),de(r.userId,e)}});function de(r,i){let e=w(D({},i),{timestamp:$e()});us.has(r)?us.get(r).push(e):us.set(r,[e])}function Ah(r){if(us.has(r)){let i=us.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return us.delete(r),i}return[]}var Rh=Ce(Pe(),1);var fa=class extends Rh.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}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:s,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let o=`peer leave [${e}]`;E(t)||(o+=`:${Za[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let s=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,d=Hi(o,n),c=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(c){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==o&&(m.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:c,muteState:d,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Hi(0,n),muteState:d,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Kd({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return j((t,s)=>{let o=new WeakMap;return T.on(g.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new b({code:S.INVALID_OPERATION,message:U({key:x.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var Ch=!0,yh=function(){var r;Ch&&(Ch=!1,y.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${wt}/en/index.html`),console.info(`* Changelog: ${wt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),y.info("TRTC Web SDK Version:",Te),y.info("UA:",navigator.userAgent),y.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),qs().then(i=>{i&&y.info(Tt)}))};var lt={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"};var V={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},kt=(C=>(C[C.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",C[C.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",C[C.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",C[C.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",C[C.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",C[C.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",C[C.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",C[C.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",C[C.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",C[C.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",C[C.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",C[C.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",C[C.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",C[C.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",C[C.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",C[C.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",C[C.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",C[C.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",C[C.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",C[C.INVALID_OPERATION=5100]="INVALID_OPERATION",C[C.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",C[C.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",C[C.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",C[C.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",C[C.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",C[C.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",C[C.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",C[C.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",C[C.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",C[C.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",C[C.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",C[C.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",C[C.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",C[C.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",C[C.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",C[C.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",C[C.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",C[C.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",C[C.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",C[C.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",C[C.DEVICE_ERROR=5300]="DEVICE_ERROR",C[C.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",C[C.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",C[C.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",C[C.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",C[C.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",C[C.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",C[C.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",C[C.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",C[C.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",C[C.SERVER_ERROR=5400]="SERVER_ERROR",C[C.NEED_TO_BUY=5401]="NEED_TO_BUY",C[C.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",C[C.OPERATION_FAILED=5500]="OPERATION_FAILED",C[C.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",C[C.REJOIN_FAILED=5502]="REJOIN_FAILED",C[C.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",C[C.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",C[C.OPERATION_ABORT=5998]="OPERATION_ABORT",C[C.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",C))(kt||{});function Nh({code:r,params:i,enableDocLink:e=!1}){let t="",s,o=kt[r];try{s=bh[o]}catch(n){s=bh.UNKNOWN_ERROR}return ie(s)?t=s(i):K(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var bh=w(D({},Ne),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${Se(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${Se(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>`role: '${"audience"}' cannot call this api.`,INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:r})=>`you need to call ${r}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:r,deviceType:i=_r(r),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function _r(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var gr=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:o,fnName:n="",originError:a}){var c;let d;s?d=s:d=Nh({code:e===V.SERVER_ERROR?e:t||e,params:D({fnName:n,error:a},o)});super(d);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=kt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=d,this.extraCode===5302&&((c=this.originError)==null?void 0:c.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");At?p.href=`ms-settings:privacy-${m[this.functionName]}`:Rt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,s){let o=e;if(e instanceof b){let{stack:n}=e,a={code:V.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=V.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=V.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=V.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ne.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=V.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=V.OPERATION_ABORT;break;case S.DEVICE_NOT_FOUND:case S.DEVICE_AUTO_RECOVER_FAILED:case S.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=E_(e.name));break;case S.UNKNOWN:break;default:a.code=V.OPERATION_FAILED}o=new gr(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
51
|
-
`)))}else{if(e instanceof gr)return e;o=new gr({code:V.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function E_(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var L=gr;var vh={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Dh={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}}},ls={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(K(r)&&!document.getElementById(r))throw new L({code:V.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Oh={name:"userId",required:!0,type:"string"},Mh={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[lt.AUDIO_PROFILE_STANDARD,lt.AUDIO_PROFILE_STANDARD_STEREO,lt.AUDIO_PROFILE_HIGH,lt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function vo(r,i){if(!r)throw new L({code:V.INVALID_OPERATION,extraCode:5101,fnName:i})}function kh(r,i,e){if(!r)throw new L({code:V.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var PN={type:"number",notLessThanZero:!0},T_={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new L({code:V.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(K(r.roomId))throw new L({code:V.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new L({code:V.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new L({code:V.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new L({code:V.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:ls,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:vh},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Ti())throw new L({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(D({},ls),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:vh}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Mh},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Ti())throw new L({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Mh}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ls,publish:{type:"boolean"},option:Dh},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&Ti())throw new L({code:V.ENV_NOT_SUPPORTED,extraCode:5201});if(!oo())throw new L({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ls,publish:{type:"boolean"},option:Dh}},muteRemoteAudio:[Oh,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Oh,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ls,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){vo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(kh(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(D({},ls),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){vo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(kh(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&E(r.streamType))throw new L({code:V.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){vo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!uo)throw new L({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new L({code:V.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new L({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new L({code:V.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});vo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new L({code:V.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new L({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new L({code:V.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(vo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new L({code:V.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},ve={TRTC:T_};var Ve=class extends Error{};function S_(r,i){let e=Qr(r);for(let t=0;t<i.length;t++)fi(e[t],i[t]);return e}function I_(r){this._resolve=Promise.resolve(r)}function A_(r){this._reject=Promise.reject(r)}var Er=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=S_;let t=Er.instances.get(i);t?t.set(e,this):Er.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Er.instances.get(i);return t&&t.get(e)||new Er(i,e)}static gets(i,e){let t=Er.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=a=>{var d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},o=a=>{var d,c;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new Ve("start failed")),(c=this.currentOp)==null||c.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:I_,reject:A_};try{switch(this.state){case 1:if(i===0)throw new Ve("already started");break;case 4:if(i===2)throw new Ve("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Ve("already start");break;case 3:switch(i.type){case 2:throw new Ve("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ve("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Ve("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new Ve("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ve("start not allowed after update");case 0:throw new Ve("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Ve("keep start")),new Ve("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},ti=Er;ti.instances=new WeakMap;var _a=new WeakMap,ga=(r,i)=>{if(i instanceof Ve){let{stack:e}=i;i=new L({code:V.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
52
|
-
`)))}throw i};function
|
|
50
|
+
} `;var pr=class extends H{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");u(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Ri(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new cs(this,e)}createVideoImageSource(e,t){return new No(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new vo(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(pr,"_ids",0);var f_={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ke=class extends pr{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${pr._ids++}`),this.ctx=this._canvas.getContext("webgl2",f_),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,m_),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,p_),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};N([he(H.INIT,"created",{sync:!0,fail(s){v.addFailedEvent({key:512700,error:s.cause})},success(){v.addSuccessEvent({key:512700})}})],ke.prototype,"create",1),N([he("created",H.INIT,{ignoreError:!0,sync:!0,success(s){s&&this.emit("unavailable",s),this.removeAllListeners()}})],ke.prototype,"destroy",1);var Qe=class extends pr{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${pr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,v.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),v.addSuccessEvent({key:512703})}};N([he(H.INIT,"created",{sync:!0,fail(s){v.addFailedEvent({key:512701,error:s.cause})},success(){v.addSuccessEvent({key:512701})}})],Qe.prototype,"create",1),N([he("created",H.INIT,{ignoreError:!0,sync:!0})],Qe.prototype,"destroy",1);function __(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var Ot=class extends ut{constructor(e,t,r=4){super(e,t,r);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}play(e,t){return(le(t==null?void 0:t.canvasRender)?t.canvasRender:ci===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new Qe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let r=new bo(e,{name:"remotePlayer",logger:this.log});t.connect(r),this.player.setCanvas(e._canvas),ho()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=__(t);if(!ee(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager?this.manager.decodePipeline.some(e=>e):!1}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce((t,r)=>r?r({frame:t,track:this}):t,e):e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},ds=class extends Ot{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};var us=new Map;T.on(E.JOIN_SUCCESS,({room:s})=>{de(s.userId,{eventId:32788})});T.on(E.LEAVE_START,({room:s})=>{de(s.userId,{eventId:32789})});T.on(E.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),de(s.room.userId,{eventId:i})}});T.on(E.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),de(s.room.userId,{eventId:i})}});T.on(E.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===h.AUDIO?de(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):de(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});T.on(E.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===h.AUDIO?de(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):de(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});T.on(E.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{!s.room||(s.mediaType===1&&de(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&de(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&de(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});T.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{!s.room||(s.mediaType===1&&de(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&de(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&de(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});T.on(E.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&de(s.room.userId,{eventId:s.kind===h.VIDEO?32780:32781})});T.on(E.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&de(s.room.userId,{eventId:s.kind===h.VIDEO?32782:32783})});T.on(E.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&de(s.userId,{eventId:t})});T.on(E.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&de(s.userId,{eventId:o,remoteUserId:t})});T.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:s,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:r,streamType:o})=>{let n=t?1:0;r||(n=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:n,param2:a,streamType:o||2};i&&(c.remoteUserId=i,c.eventId=4005),de(s,c),v.addEnum({key:i?514701:513701,value:n}),v.addEnum({key:i?514700:513700,value:a})});T.on(E.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),de(s.userId,e)}});function de(s,i){let e=x(D({},i),{timestamp:ot()});us.has(s)?us.get(s).push(e):us.set(s,[e])}function Sh(s){if(us.has(s)){let i=us.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return us.delete(s),i}return[]}var Ih=ye(xe(),1);var pa=class extends Ih.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;g(t)||(o+=`:${Za[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=$i(o,n),d=(l=this.remotePublishedUserMap.get(r))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(r);m&&m.flag!==o&&(m.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:$i(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Zd({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return j((t,r)=>{let o=new WeakMap;return T.on(E.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new b({code:S.INVALID_OPERATION,message:U({key:w.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var Ah=!0,Ch=function(){var s;Ah&&(Ah=!1,y.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Lt}/en/index.html`),console.info(`* Changelog: ${Lt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),y.info("TRTC Web SDK Version:",Ie),y.info("UA:",navigator.userAgent),y.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Xs().then(i=>{i&&y.info(Tt)}))};var fr={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"};var V={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Mt=(R=>(R[R.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",R[R.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",R[R.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",R[R.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",R[R.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",R[R.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",R[R.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",R[R.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",R[R.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",R[R.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",R[R.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",R[R.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",R[R.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",R[R.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",R[R.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",R[R.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",R[R.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",R[R.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",R[R.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",R[R.INVALID_OPERATION=5100]="INVALID_OPERATION",R[R.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",R[R.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",R[R.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",R[R.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",R[R.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",R[R.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",R[R.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",R[R.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",R[R.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",R[R.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",R[R.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",R[R.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",R[R.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",R[R.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",R[R.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",R[R.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",R[R.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",R[R.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",R[R.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",R[R.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",R[R.DEVICE_ERROR=5300]="DEVICE_ERROR",R[R.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",R[R.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",R[R.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",R[R.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",R[R.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",R[R.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",R[R.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",R[R.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",R[R.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",R[R.SERVER_ERROR=5400]="SERVER_ERROR",R[R.NEED_TO_BUY=5401]="NEED_TO_BUY",R[R.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",R[R.OPERATION_FAILED=5500]="OPERATION_FAILED",R[R.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",R[R.REJOIN_FAILED=5502]="REJOIN_FAILED",R[R.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",R[R.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(Mt||{});function yh({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Mt[s];try{r=Rh[o]}catch(n){r=Rh.UNKNOWN_ERROR}return ie(r)?t=r(i):Y(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Rh=x(D({},Ne),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>`role: '${"audience"}' cannot call this api.`,INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:s,deviceType:i=_r(s),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function _r(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Er=class extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var d;let c;r?c=r:c=yh({code:e===V.SERVER_ERROR?e:t||e,params:D({fnName:n,error:a},o)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Mt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");ni?p.href=`ms-settings:privacy-${m[this.functionName]}`:At&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof b){let{stack:n}=e,a={code:V.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=V.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=V.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=V.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ne.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=V.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=V.OPERATION_ABORT;break;case S.DEVICE_NOT_FOUND:case S.DEVICE_AUTO_RECOVER_FAILED:case S.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=E_(e.name));break;case S.UNKNOWN:break;default:a.code=V.OPERATION_FAILED}o=new Er(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
51
|
+
`)))}else{if(e instanceof Er)return e;o=new Er({code:V.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function E_(s){let i;switch(s){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var L=Er;var bh={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Nh={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}}},ls={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(Y(s)&&!document.getElementById(s))throw new L({code:V.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},vh={name:"userId",required:!0,type:"string"},Dh={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:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Do(s,i){if(!s)throw new L({code:V.INVALID_OPERATION,extraCode:5101,fnName:i})}function Oh(s,i,e){if(!s)throw new L({code:V.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var ON={type:"number",notLessThanZero:!0},g_={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new L({code:V.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(Y(s.roomId))throw new L({code:V.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new L({code:V.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new L({code:V.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new L({code:V.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:ls,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:bh},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Ei())throw new L({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:x(D({},ls),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:bh}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Dh},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Ei())throw new L({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Dh}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ls,publish:{type:"boolean"},option:Nh},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)&&Ei())throw new L({code:V.ENV_NOT_SUPPORTED,extraCode:5201});if(!no())throw new L({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ls,publish:{type:"boolean"},option:Nh}},muteRemoteAudio:[vh,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[vh,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ls,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){Do(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Oh(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:x(D({},ls),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){Do(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Oh(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&g(s.streamType))throw new L({code:V.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Do(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!lo)throw new L({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new L({code:V.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new L({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new L({code:V.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Do(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new L({code:V.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new L({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new L({code:V.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Do(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new L({code:V.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},De={TRTC:g_};var Ve=class extends Error{};function T_(s,i){let e=Xr(s);for(let t=0;t<i.length;t++)pi(e[t],i[t]);return e}function S_(s){this._resolve=Promise.resolve(s)}function I_(s){this._reject=Promise.reject(s)}var gr=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=T_;let t=gr.instances.get(i);t?t.set(e,this):gr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=gr.instances.get(i);return t&&t.get(e)||new gr(i,e)}static gets(i,e){let t=gr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Ve("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:S_,reject:I_};try{switch(this.state){case 1:if(i===0)throw new Ve("already started");break;case 4:if(i===2)throw new Ve("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Ve("already start");break;case 3:switch(i.type){case 2:throw new Ve("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ve("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Ve("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 Ve("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ve("start not allowed after update");case 0:throw new Ve("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Ve("keep start")),new Ve("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}},ei=gr;ei.instances=new WeakMap;var fa=new WeakMap,_a=(s,i)=>{if(i instanceof Ve){let{stack:e}=i;i=new L({code:V.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
52
|
+
`)))}throw i};function qi(s,i){return j((e,t)=>function(...r){let o=ei.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(_a.bind(null,t))):e.apply(this,r)})}function Tr(s,i){let{merge:e,debounce:t}=i||{};return j((r,o)=>function(...n){let a=ei.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=t;return new Promise((l,m)=>{var I,A;let p=(I=fa.get(this))==null?void 0:I.get(d(...n));if(p){let{timeoutId:C,resolve:F}=p;clearTimeout(C),F()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,r.bind(this),n).catch(_a.bind(null,o)).then(l,m)},c);fa.has(this)?(A=fa.get(this))==null||A.set(d(...n),{timeoutId:_,resolve:l}):fa.set(this,new Map([[d(...n),{timeoutId:_,resolve:l}]]))})}return a.action(2,r.bind(this),n).catch(_a.bind(null,o))})}function Xi(s){return j((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(ei.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=ei.get(this,r);return o?o.action(3,i.bind(this),t).catch(_a.bind(null,e)):i.apply(this,t)})}var M={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",NETWORK_TIME_UPDATED:"network-time-updated"},Mh=new Set([M.ERROR,M.AUTOPLAY_FAILED,M.KICKED_OUT,M.REMOTE_USER_ENTER,M.REMOTE_USER_EXIT,M.REMOTE_AUDIO_AVAILABLE,M.REMOTE_AUDIO_UNAVAILABLE,M.REMOTE_VIDEO_AVAILABLE,M.REMOTE_VIDEO_UNAVAILABLE,M.CONNECTION_STATE_CHANGED,M.PUBLISH_STATE_CHANGED,M.SCREEN_SHARE_STOPPED,M.DEVICE_CHANGED]);function Oo(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function Sr(s){return s===fr.QOS_PREFERENCE_CLEAR?"detail":s===fr.QOS_PREFERENCE_SMOOTH?"motion":""}var A_=s=>s.startsWith("data:application/octet-stream;base64,"),C_=s=>s.startsWith("file://"),Ea=class{constructor(){u(this,"_log");this._log=y.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};try{let r=P(),o;if(ie(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=P()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:P()-r}),o.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)throw new Error("network response was not ok");let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):r(new Error("XHR failed"))},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=P(),r=null,o=null;if(ie(WebAssembly.instantiateStreaming)&&!A_(i)&&!C_(i)&&ie(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=P()-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: ${o}`),v.addFailedEvent({key:522701,error:o}),o})}};N([je({settings:{timeout:0,retries:3},onRetrying(s){this._log.warn(`download retrying: ${s}`)}})],Ea.prototype,"download",1);var kh=new Ea;function Ph({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:kh,innerEmitter:T,INNER_EVENT:E,constants:ec,environment:Jr,utils:Fe,eventLogger:K,log:this.room.getLogger(),loggerManager:y,errorModule:e,kvStatManager:v,rtcDectection:Wt,trtc:this,audioContext:ve(),deviceDetector:ge,AudioPlayer:Ji,AutoPlayDialog:Hn,Timer:Z,Enum:uc,clearStarted:(r,o)=>{let n=r.getAlias(),a=ei.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})},startGetPCM:Ro,createAudioNode:id,getNetworkTimeOffset:ju}}var Lh=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=U({key:w.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return y.warn(`${o}
|
|
53
53
|
|
|
54
|
-
${s.stack}`),!1}},r};var Ta=new WeakMap;function Uh(r,i){return j((e,t)=>function(...s){var a,d;let o=(a=Ta.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Ta.has(this)?(d=Ta.get(this))==null||d.set(i(...s),n):Ta.set(this,new Map([[i(...s),n]]))})}var Vh="5.8.5-ktv.2";function Be(...r){return j((i,e)=>function(...t){try{Ia.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function eu(...r){return j((i,e)=>function(...t){try{Ia.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ia(r,i,e,t){if(_e(r))for(let s=0;s<r.length;s++)Sa.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Sa.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Sa({rule:r,value:i,key:e,fnName:t,className:s}){function o(d){return{code:V.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new L(o(5001));if(E(r.defaultValue)){ie(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let d=!1;for(let c=0;c<r.type.length;c++)r.type[c]===null&&i===null&&(d=!0),ie(r.type[c])&&i instanceof r.type[c]&&(d=!0),K(r.type[c])&&Se(i)===r.type[c].toLowerCase()&&(d=!0);if(!d)throw new L({code:V.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(c=>Ks(c)?Cn(c):K(c)?c:Se(c))},value:i}})}else if(!E(r.type)&&Se(i)!==r.type)throw new L(o(5002));if(r.allowEmpty===!1){let d=te(i)&&(i===0||Number.isNaN(i)),c=K(i)&&i.trim()==="";if(d||c)throw new L(o(5003))}if(r.notLessThanZero&&te(i)&&i<0)throw new L(o(5006));if(!E(r.min)&&te(i)&&i<r.min)throw new L(o(5007));if(!E(r.max)&&te(i)&&i>r.max)throw new L(o(5008));if(K(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new L(o(5004))}else if(ie(r.instanceOf)&&!(i instanceof r.instanceOf))throw new L(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new L(o(5005));let{properties:n}=r;et(n)&&bt(i)&&Object.keys(n).forEach(d=>{Sa.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:s})});let{arrayItem:a}=r;et(a)&&_e(i)&&i.forEach((d,c)=>{Sa.call(this,{rule:a,value:d,key:`${e}[${c}]`,fnName:t,className:s})}),ie(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ae(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return j((s,o)=>function(...n){var l;function a(m,p,_){if(_&&_.includes(m))return"hided";if(e){let I=e(...n);if(n[I.argIndex]===p)return I.value}if(p===n||m in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${Se(p)}`:(JSON.stringify(p),p)}catch(I){return`type:${Se(p)}`}}let d=this._log||y;n.length>0?d.info(`${o}() ${JSON.stringify(n,(m,p)=>a(m,p,["userSig","privateMapKey"]))}`):d.info(`${o}()`);let c=t?t(...n):On[o];try{let m=s.apply(this,n),p=P();return ar(m)?m.then(_=>(d.info(`${o}() success ${i.call(this,...n)}`),v.addSuccessEvent({key:c,cost:P()-p}),_)).catch(_=>{var R;_=L.convertFrom.call(this,_,o,n.length===1?n[0]:n);let I=_.extraCode||_.code,A=(R=_.message)!=null&&R.includes(I)?"":` code:${I}`;throw d.error(`${o}() failed ${i.call(this,...n)} ${_}${A} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:c,error:_}),_}):(v.addSuccessEvent({key:c}),m)}catch(m){m=L.convertFrom.call(this,m,o);let p=m.extraCode||m.code,_=(l=m.message)!=null&&l.includes(p)?"":` code:${p}`;throw d.error(`${o}() failed ${m}${_} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:c,error:m}),m}})}var Aa=r=>j((i,e)=>function(t,s){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new L({code:V.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ie(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new L({code:V.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Ia.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Ra=0,tu=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new ts(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function hs(r,i){if(i&&typeof i!="function")throw new L({code:V.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var ms=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Ra=Ra+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ra}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ra}`),this.core=i}getName(){return ms.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ms.startValidateRule;case"update":return ms.updateValidateRule;case"stop":return ms.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new tu(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),E(t)||n.setOperation(t),E(s)||n.seek(s),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:c,onEnded:l}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),s&&v.addCount({key:502704}),o&&v.addCount({key:502705}),n&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof d!="function"&&v.addCount({key:502709}),typeof l!="function"&&v.addCount({key:502710}),typeof c!="function"&&v.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Yi=ms;u(Yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,d=s.startsWith("blob"),c=s.startsWith("data");if(!(a||d||c))throw new L({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new L({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});hs("onTimeUpdate",i.onTimeUpdate),hs("onEnded",i.onEnded),hs("onDurationChange",i.onDurationChange)}}),u(Yi,"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){hs("onTimeUpdate",i.onTimeUpdate),hs("onEnded",i.onEnded),hs("onDurationChange",i.onDurationChange)}}),u(Yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Yi,"Name","AudioMixer");var b_=r=>(r=Number(r),r>0&&r<14e8),Ca=0,iu,ps=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",xe("denoiser"));u(this,"workletNode");Ca=Ca+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ca}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ca}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new L({code:V.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return iu||(iu=this.doPreload(i)),iu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield lr(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return ps.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return ps.startValidateRule(this.core);case"update":return ps.updateValidateRule;case"stop":return ps.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield v_(w(D({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new L({code:V.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=d=>{let{data:c}=d;c.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${c.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},Ir=ps;u(Ir,"updateValidateRule",{type:"object"}),u(Ir,"stopValidateRule",{type:"object"}),u(Ir,"Name","AIDenoiser");var Bh={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function N_(r){let i;return b_(r)?i=Bh.MAIN_OVERSEA:i=Bh.MAIN,i}function v_(s){return f(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${N_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:c,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:c};let p="Init RTCAIDenoiser failed.",_="";switch(d){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:m,message:c?`${p} Reason: ${c}. ${_}`:`${p}, ${_}`}})}var Fh=Ce(Pe(),1);var ru=class extends Fh.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&y.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},D_=new ru,su=D_;function ou([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ri(new DataView(new Uint8Array(o).buffer),!0)}function nu(r){return r.type==="empty"||r.data.byteLength===0}function au(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function cu(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function du({frame:r,seiMessageList:i}){if(!i||i.length===0||r.data.byteLength===0)return r;let e=cu(r.data),t=9-e;if(t<=0)return r;let s=i.splice(0,t).reverse().map(ou),o=s.reduce((l,m)=>l+m.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),d=new DataView(r.data),c=0;for(let l=0;l<s.length;l++)for(let m=0;m<s[l].dataView.byteLength;m++)a.setInt8(c++,s[l].dataView.getInt8(m));for(let l=0;l<r.data.byteLength;l++)a.setInt8(c++,d.getInt8(l));return r.data=n,r}function uu({frame:r,onSEI:i}){try{let e=new DataView(r.data);if(nu(r)||!au(e))return r;let t=[],s=0,o=-1,n=-1;for(let a=0;a<r.data.byteLength;a++){let d=e.getUint8(a);if(d===0)s++;else if(d===1){if(s===2||s===3){let c=a-s;if(o===-1?o=c:n===-1&&(n=c,t.push(new Ri(new DataView(e.buffer.slice(o,n)))),o=c,n=-1),!(e.getUint8(a+1)===6)){r.data=e.buffer.slice(c);break}}s=0}else s=0}i==null||i(t.reverse())}catch(e){}return r}var lu=0,hu=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);lu++,this.log=i.log.createChild({id:`${this.getAlias()}${lu}`}),this.log.info(`[sei] created id=${this.getAlias()}${lu}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return du({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return uu({frame:i,onSEI:t=>{t.forEach(s=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Dt?this.encode:du,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:Dt?this.decode:uu,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:s})}getName(){return hu.Name}getAlias(){return"sei"}getGroup(){return"sei"}},fs=hu;u(fs,"autoStart",!0),u(fs,"Name","SEI");var O_=0,ya,mu=class{constructor(i){this.core=i;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++O_}`}),this.log.info("created")}getName(){return mu.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*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){try{if(ya)yield ya;else{let i=Date.now();ya=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Te}.js`),yield ya,this.log.info(`download debug dialog script cost: ${Date.now()-i}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo({frame:i,mediaType:e}){return this.encodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",s=this.dumpLocalVideoMap[t];s&&(s.data.push(i.data),s.duration>0&&Date.now()-s.startTimestamp>s.duration*1e3&&s.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return this.decodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}encodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}decodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let s=document.createElement("script");s.type="text/javascript",s.onload=e,s.onerror=t,s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}},Ar=mu;u(Ar,"Name","Debug"),u(Ar,"autoStart",!0),N([qe({settings:{timeout:3e3,retries:3},onError(r,i,e){var t;(t=r==null?void 0:r.message)!=null&&t.includes("timeout")?i():e(r)}})],Ar.prototype,"loadScript",1);var $h=0,ba=new Set,De=null;$a(Vh);var M_={RtcError:L,ErrorCode:V,ErrorCodeDictionary:kt},ii=class extends Hh.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",y.createLogger({id:`t${++$h}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"_getPCMAbortCtrl");this._room=new e(D({logger:this._log,frameWorkType:ii.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Yi,t.assetsPath),this._use(Ir,t.assetsPath),this._use(Ar),t.enableSEI&&uo&&this._use(fs),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(M.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",s=>{this._log.error(new L({code:V.OPERATION_FAILED,extraCode:5504,message:s.message,originError:s}))}),this._listenEvents(),this._initActiveSpeaker(),xh(this,"trtc")}static create(e){}static _create(e,t){yh();let s=new ii(e,t||{});return ba.add(s),s}get room(){return this._room}_listenEvents(){we(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,L.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=w(D({},e),{uplinkRTT:Math.min(e.uplinkRTT,Ps),downlinkRTT:Math.min(e.downlinkRTT,Ps)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{we(s,s).add("player-state-changed",o=>{let n=w(D({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=Do(s.streamType)),this.emit(s.kind===h.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{ge(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(s),d||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==d&&(T.emit(d?"254":"255",{userId:s,streamType:"main",room:this.room}),this.emit(d?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),d?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,w(D({},e),{streamType:Do(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new L({code:V.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,d,c,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Ps),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((c=this._networkQuality)==null?void 0:c.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/at},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/at},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(M.STATISTICS,s)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}).add("ntp-time-updated",()=>{this.emit(M.NETWORK_TIME_UPDATED,{networkTime:$e()})}),we(this,Re).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),De&&De.deviceId===ks){let t=(yield ji()).find(s=>s.deviceId===ks);t&&De.groupId!==t.groupId&&(De=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield ji())[0];if(!t||!De||De.groupId===t.groupId)return;let s=De.deviceId===e.deviceId,o=De.deviceId===ks&&De.deviceId===t.deviceId;(s||o)&&(De=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}getNetworkTime(){return $e()}use(e){let t,s;return"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){let s=this._plugins.get(e.Name);if(s)return this._log.warn("duplicate install plugin",e.Name),s;let o=new e(wh.call(this,{TRTC:ii,room:this._room,errorModule:M_,assetsPath:t}));return this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name),o}enterRoom(e){return f(this,null,function*(){var d,c;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!K(e.proxy)&&e.proxy.turnServer&&((c=(d=this._room).setTurnServer)==null||c.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,le(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,ii.frameWorkType),this._checkTrackToPublish(),su.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){ge(this),this.removeAllListeners(),this._room.destroy(),ba.delete(this),ba.size===0&&su.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:o}=e,n=new Ue(this._room.audioManager),a={},d={muted:!0};o&&(E(o.microphoneId)?E(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&te(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),E(o.profile)||(K(o.profile)?Qo[o.profile]&&n.setProfile(Qo[o.profile]):n.setProfile(o.profile)),te(o.earMonitorVolume)&&(d.muted=!(o.earMonitorVolume>0),d.volume=o.earMonitorVolume),E(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),E(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),E(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",c=>{this.emit(M.ERROR,new L({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:c}}))}),n.on("2",c=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:c})}),n.on("4",c=>{let l;c.error&&(l=L.convertFrom(c.error)),this.emit(M.PUBLISH_STATE_CHANGED,w(D({},c),{error:l}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),E(s)||n.setMute(s),we(n,n).add("player-state-changed",c=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,w(D({},c),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(c=>{this.emit(ii.EVENT.AUDIO_FRAME,{data:c})})),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(D({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):E(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),E(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),E(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),fi(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ge(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:o,option:n}=e,a=new me(this._room.videoManager),d={},c={};if(n&&(n.cameraId?d.deviceId=n.cameraId:E(n.useFrontCamera)?E(n.videoTrack)||(d.customSource=n.videoTrack):d.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(n.profile)||(K(n.profile)?nt[n.profile]&&a.setProfile(nt[n.profile]):a.setProfile(n.profile)),E(n.fillMode)||(c.objectFit=n.fillMode),E(n.mirror)||(c.mirror=n.mirror),E(n.small)||(no()?K(n.small)?a.small=nt[n.small]:n.small===!0?a.small=nt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit(M.ERROR,new L({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=L.convertFrom(l.error)),this.emit(M.PUBLISH_STATE_CHANGED,w(D({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(d),E(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let l=Sr(n.qosPreference);a.mediaTrack.contentHint=l}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=Sr(lt.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}we(a,a).add("player-state-changed",l=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,w(D({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=w(D({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:c,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(E(n.profile)||(K(n.profile)?nt[n.profile]&&this._localVideoTrack.setProfile(nt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&E(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):E(n.useFrontCamera)?E(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(n.fillMode)||(a.objectFit=n.fillMode),E(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let d=Sr(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=d,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=d)}if(n.small){let d=!this._localVideoTrack.small;no()?(n.small===!0?this._localVideoTrack.small=nt["120p"]:K(n.small)?this._localVideoTrack.small=nt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),d&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),fi(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(),ge(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:o}=e,n=new st(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=L.convertFrom(m.error)),this.emit(M.PUBLISH_STATE_CHANGED,w(D({},m),{error:p}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,d={},c={};o&&(E(o.profile)||(K(o.profile)?zo[o.profile]&&n.setProfile(zo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(d.systemAudio=!0,d.echoCancellation=o.echoCancellation,d.noiseSuppression=o.noiseSuppression,d.autoGainControl=o.autoGainControl),E(o.fillMode)||(c.objectFit=o.fillMode),o.videoTrack&&(d.videoTrack=o.videoTrack),o.audioTrack&&(d.audioTrack=o.audioTrack),o.captureElement&&(d.captureElement=o.captureElement),o.preferDisplaySurface&&(d.preferDisplaySurface=o.preferDisplaySurface));let l=yield n.capture(d);if(o!=null&&o.qosPreference){let m=Sr(o.qosPreference);n.mediaTrack.contentHint=m}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=Sr(lt.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new Kt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),we(n,n).add("player-state-changed",m=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,w(D({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[n];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=w(D({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:c,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(E(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=Sr(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),fi(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let d=this._room.remotePublishedUserMap.get(s);if(!d)return;let c={},l=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),n&&(E(n.fillMode)||(c.objectFit=n.fillMode),E(n.mirror)||(c.mirror=n.mirror),c.canvasRender=n.canvasRender,o==="main"&&!E(n.small)&&(d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:c,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var R,$;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,d=this._remoteVideoConfigMap.get(a);if(!d||!this._room.remotePublishedUserMap.has(s))return;let c={};n&&(E(n.fillMode)||(c.objectFit=n.fillMode),E(n.mirror)||(c.mirror=n.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),o==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:p}=d;o==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:c,track:l,prevConfig:p}),fi(p,e);let _=E(n==null?void 0:n.receiveWhenViewVisible)?(R=p.option)==null?void 0:R.receiveWhenViewVisible:n.receiveWhenViewVisible,I=E(t)?p.view:t,A=E(n==null?void 0:n.viewRoot)?($=p.option)==null?void 0:$.viewRoot:n.viewRoot;this._observeView({remoteTrack:l,view:I,receiveWhenViewVisible:_,viewRoot:A})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:d,remoteAuxiliaryTrack:c}=o;e.streamType==="main"&&(d.stop(),a.hasVideo&&s.push(d)),e.streamType==="sub"&&(c.stop(),a.hasAuxiliary&&s.push(c))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),e===ii.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(ii.EVENT.AUDIO_FRAME,{data:o})})),this)}emit(e,...t){try{Ph.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(s){}return super.emit(e,...t)}off(e,t,s){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,s),e===ii.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,s=null,o="main",n=!1;if(K(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(s=a.remoteAudioTrack)}else s=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return s?n&&s.outMediaTrack&&s.outMediaTrack!==s.mediaTrack?s.outMediaTrack.clone():s.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main",processed:o=!1}=e,n=null;if(t==="")s==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),s==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=s==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield ji()).forEach(s=>{s.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}),De=s)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(E(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(d){throw this._remoteAudioConfigMap.delete(t),d}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),E(e)&&o&&o.view&&!Nc(t)){let a=eo(o.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=eo(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(M.TRACK,{userId:s,streamType:Do(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:o}){if(E(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Do(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||_e(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let c=n.visibleViewMap||new Map,l=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),c.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{c.set(_.target,_.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...c.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(eo(t));c.forEach((p,_)=>{m.has(_)||(a.unobserve(_),c.delete(_))}),m.forEach(p=>{c.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{c.set(p.target,p.isIntersecting)}),n.visibleViewMap=c,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{ge(e.remoteAudioTrack),ge(e.remoteVideoTrack),ge(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ge(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(De&&!rs(De))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:De});else{let e=yield ji();if(e[0]&&!rs(e[0]))De=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!De||rs(De))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:w(D({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),v.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){y.setLogLevel(e),E(t)||(t?y.enableUploadLog():y.disableUploadLog())}static isSupported(){return Ln()}static getCameraList(e=!0){return it(e)}static getMicrophoneList(e=!0){return Xe(e)}static getSpeakerList(e=!0){return ji(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield ji()).forEach(s=>{s.deviceId===e&&(ba.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),De=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(dr.version=a),e){case"count":dr.addCount({key:t,useUV:n});break;case"enum":dr.addEnum({key:t,value:s,useUV:n});break;case"number":dr.addNumber({key:t,value:s,split:o});break}}},z=ii;u(z,"_loggerManager",y),u(z,"EVENT",M),u(z,"ERROR_CODE",V),u(z,"TYPE",lt),u(z,"frameWorkType",30),N([ae({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],z.prototype,"use",1),N([Be(ve.TRTC.enterRoom),Qi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),j(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ae()],z.prototype,"enterRoom",1),N([ae()],z.prototype,"exitRoom",1),N([Be(ve.TRTC.switchRole),Tr("room",{merge:(r,i)=>i}),ae()],z.prototype,"switchRole",1),N([ae()],z.prototype,"destroy",1),N([Be(ve.TRTC.startLocalAudio),Qi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ae()],z.prototype,"startLocalAudio",1),N([Be(ve.TRTC.updateLocalAudio),Tr("audio",{debounce:{delay:200,getKey:()=>`${$h}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ae()],z.prototype,"updateLocalAudio",1),N([zi("audio"),ae()],z.prototype,"stopLocalAudio",1),N([Be(ve.TRTC.startLocalVideo),Qi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ae()],z.prototype,"startLocalVideo",1),N([Be(ve.TRTC.updateLocalVideo),Tr("video"),ae()],z.prototype,"updateLocalVideo",1),N([zi("video"),ae()],z.prototype,"stopLocalVideo",1),N([Be(ve.TRTC.startScreenShare),Qi("screen",()=>!0),ae()],z.prototype,"startScreenShare",1),N([Be(ve.TRTC.updateScreenShare),Tr("screen"),ae()],z.prototype,"updateScreenShare",1),N([ae()],z.prototype,"stopScreenShare",1),N([Be(ve.TRTC.startRemoteVideo),Qi(r=>`v${r.userId}${r.streamType}`,()=>!0),ae({getRemoteId:r=>`${r.userId}_${r.streamType}`})],z.prototype,"startRemoteVideo",1),N([Be(ve.TRTC.updateRemoteVideo),Tr(r=>`v${r.userId}${r.streamType}`),ae({getRemoteId:r=>`${r.userId}_${r.streamType}`})],z.prototype,"updateRemoteVideo",1),N([Be(ve.TRTC.stopRemoteVideo),j(r=>function(i){return f(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ae({getRemoteId:r=>`${r.userId}_${r.streamType}`})],z.prototype,"stopRemoteVideo",1),N([zi(r=>`v${r.userId}${r.streamType}`)],z.prototype,"_stopRemoteVideo",1),N([Be(...ve.TRTC.muteRemoteAudio),ae({getRemoteId:r=>r})],z.prototype,"muteRemoteAudio",1),N([eu(...ve.TRTC.setRemoteAudioVolume),Uh(200,r=>r),ae({getRemoteId:r=>r})],z.prototype,"setRemoteAudioVolume",1),N([Aa("start"),Ot(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Qi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ae({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Uc[r.getName()]})],z.prototype,"startPlugin",1),N([Aa("update"),Tr((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ae({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Vc[r.getName()]})],z.prototype,"updatePlugin",1),N([Aa("stop"),zi((r,i)=>{if(r.disableRandomCall)return null;let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ae({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Bc[r.getName()]})],z.prototype,"stopPlugin",1),N([eu(...ve.TRTC.enableAudioVolumeEvaluation)],z.prototype,"enableAudioVolumeEvaluation",1),N([ae()],z.prototype,"getVideoSnapshot",1),N([ae()],z.prototype,"_setCurrentSpeaker",1),N([Qi(r=>`a${r.userId}`,()=>!0)],z.prototype,"_startRemoteAudio",1),N([j(r=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(w(D({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),zi(r=>`a${r.userId}`)],z.prototype,"_stopRemoteAudio",1),N([zi("room")],z.prototype,"_exitRoom",1),N([zi("screen")],z.prototype,"_stopScreenShare",1),N([Be(...ve.TRTC.sendSEIMessage),Kd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],z.prototype,"sendSEIMessage",1),N([Be(ve.TRTC.sendCustomMessage),Kd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],z.prototype,"sendCustomMessage",1),N([Be(ve.TRTC.create)],z,"_create",1);var Oo=z;var pu=class{constructor(){this._set=new Set;T.on(g.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function k_(){return f(this,null,function*(){let r,i;try{let m=yield Xe();r=m&&m.length}catch(m){}try{let m=yield it();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Jt.basis(),d={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},c={browser:a.browser,os:a.os,trtc:d,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(c)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(c)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Gh(){return j(r=>{let i=new pu;return function(e,t,s){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:S.INVALID_OPERATION,message:U({key:x.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:S.INVALID_OPERATION,message:U({key:x.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(g.JOIN_START,{room:this,roomId:o,params:e});let n=He.getEnv();n||(n=oi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Yo.OLD_CLOUD_LADDER)?n=oi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Yo.WEBRTC)&&(n=oi.WEBRTC))),Z.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Jt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,k_.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!He.getEnv()&&(yield this.schedule(e,s));let a=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=He.performanceNow(),T.emit(g.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(ui)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(g.JOIN_FAILED,{room:this,error:a}),a}})}})}var Wh=()=>j(r=>function(...i){return f(this,null,function*(){T.emit(g.LEAVE_START,{room:this}),yield r.call(this),T.emit(g.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Jh(){return j(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var qh=Ce(Pe());var pe={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var ht={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,UPDATE_NETWORK_TIME_RESULT:5001},jh=[ht.UPDATE_REMOTE_MUTE_STAT,ht.UPLINK_NETWORK_STATS,ht.USER_LIST_RES,ht.MUTE_RESULT,ht.SERVER_FIRST_PACKAGE_RECEIVED,ht.RECEIVE_CUSTOM_MSG,ht.UPDATE_NETWORK_TIME_RESULT],B={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",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",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",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",UPDATE_NETWORK_TIME:"update_network_time"};var Na=new Set;function Xh(r){let i=[...Na.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var _s=class extends qh.default{constructor(e){var s,o;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");u(this,"stopKeepAliveTimeout");u(this,"rtt",0);this.room=e.room,this.race=E(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Na.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Na.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=y.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=P();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 zs(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,d)=>{o.onclose=d,o.onerror=d,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),d(new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse){if(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}this.room.isJoining&&this.emit(pe.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"}))}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(pe.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=yn(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(ht),d=Object.keys(ht)[n.indexOf(s)],c=B[d]||s;switch(jh.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),c&&this._log.info(`Received event: [ ${c} ]`)),s){case ht.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:P()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(pe.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:U({key:x.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:l}),this.emit(pe.SETUP_FAILED,l)}break}case ht.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(c,{data:t});break}default:this.emit(String(c),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;$t(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:B.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:P()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=yn(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((c,l)=>{let m=setTimeout(()=>{this.off(o,p);let I=new b({code:S.API_CALL_TIMEOUT,message:U({key:x.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(I),l(I)},s),p=I=>{I.data.seq===_&&(clearTimeout(m),this.off(o,p),d&&(I.data.receiveTime=Date.now()),c(I))};this.on(o,p);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return Ft({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(pe.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Na.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(B.JOIN_ROOM_RESULT,t)},e*1e3);let t=s=>{s.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(B.JOIN_ROOM_RESULT,t))};this.on(B.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(pe.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(pe.CONNECTED):e==="DISCONNECTED"&&this.emit(pe.DISCONNECTED))}};N([qe({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],_s.prototype,"connect",1);var Qh=Ce(Pe());var fu=0,_u=!1,va=new Set,L_=r=>fu>2&&!_u&&va.size===0&&r,gu=!1,Ge=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new Qh.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=y.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=P())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(P()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:P()-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(),va.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new b({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ft;let i=null;if(this._isUplink){if(!Ji()||this._peerConnection.getSenders().length===0)return ft;i=this._peerConnection.getSenders()[0].transport}else{if(!ur()||this._peerConnection.getReceivers().length===0)return ft;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ft}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===ne.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ne.FAILED||i.target.connectionState===ne.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:s,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===ne.CONNECTED||i.target.connectionState===ne.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:We.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(fu=0,_u=!1,gu=!0,va.add(this)):va.delete(this),T.emit(g.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(Wi(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(g.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});fu+=1,L_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),_u=!0,this._emitter.emit("firewall-restriction")),e(a)},Ms);T.on(g.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(pe.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=ni()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:U({key:this._isUplink?x.UPLINK_RECONNECTION_FAILED:x.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(pe.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)}};N([Qe(521712,!1)],Ge.prototype,"setOffer",1),N([Qe(521713,!1)],Ge.prototype,"setAnswer",1);var Iu=Ce(Su());var ue=function(r){return Iu.default.parse(r)},mt=function(r){return Iu.default.write(r)},rm=function(r){let i=ue(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),mt(i)};function sm(r){let i=ue(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let c=d.match(/apt=(\d+)/);c&&c[1]&&o.has(Number(c[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),mt(i)}function Da(r){return Object.keys(r).filter(i=>r[i])}var Ru=class extends Ge{constructor(e){super(w(D({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"isRobot",!1);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ci(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Mt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ds(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Hi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===Os?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
|
|
55
|
-
`),
|
|
56
|
-
`)}addSPSDescription(e){let t=ue(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),mt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=ue(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),mt(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===ne.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===ne.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=D({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Da(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new b({code:a.code,message:U({key:x.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:B.SUBSCRIBE_RESULT,timeout:Ya});if(!this._peerConnection){let a=new b({code:S.INVALID_OPERATION,message:U({key:x.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};ct()&&this._sdpSemantics===ki?(this._peerConnection.addTransceiver(h.AUDIO,{direction:Y.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Y.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Y.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield Pn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=sm(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=rm(t.sdp),this._sdpSemantics===ki&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===tr)throw new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:U({key:x.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ue(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Os)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(Os)}),n=s.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(ja)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(ye(Ru.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=Ht(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}setAudioJitterBuffer(e){if(!this._peerConnection)return;let t=this._peerConnection.getReceivers()[0];!t||(this._log.warn(`setAudioJitterBuffer ${e}`),t.jitterBufferTarget=e)}},Es=Ru;N([j(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Es.prototype,"subscribe",1),N([Qe(521717,!1)],Es.prototype,"unsubscribe",1),N([Ot(Ge.prototype.afterConnect),Qn(Ge.prototype.beforeConnect)],Es.prototype,"connect",1);var Au=Es;var nm={voiceActivityDetection:!1},Cu=class extends Ge{constructor(e){super(w(D({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Gt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,d;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),ct()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,c=e==null?void 0:e.outMediaTrack;c&&a.addTrack(c),d&&a.addTrack(d);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(c||h.AUDIO,{direction:Y.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:d||h.VIDEO,{direction:Y.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:Y.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?d||h.VIDEO:h.VIDEO,{direction:Y.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(c&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),d){let p=o?3:1;yield l[p].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),m.push(p),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(Y.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),s)){let c=new MediaStream;c.addTrack(s),this._peerConnection.addTrack(s,c)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Y.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Y.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Gt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(D({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(D({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(Y.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Wt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),ct()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Y.INACTIVE&&(yield this.setTransceiverDirection(Y.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Gt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof me&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Or||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ue(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;Gt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ie(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),ct()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Y.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!se)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(c=>{n[c].direction!==e&&(n[c].direction=e,s=!0)}),s){this._log.info("updating offer");let c=yield this._peerConnection.createOffer();yield this.setOffer(c)}let a=-1,d=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
57
|
-
`).map(
|
|
58
|
-
`);o&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:
|
|
59
|
-
`:
|
|
54
|
+
${r.stack}`),!1}},s};var ga=new WeakMap;function xh(s,i){return j((e,t)=>function(...r){var a,c;let o=(a=ga.get(this))==null?void 0:a.get(i(...r));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,r)},s);ga.has(this)?(c=ga.get(this))==null||c.set(i(...r),n):ga.set(this,new Map([[i(...r),n]]))})}var wh="5.8.5-ktv.21";function Be(...s){return j((i,e)=>function(...t){try{Sa.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function tu(...s){return j((i,e)=>function(...t){try{Sa.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function Sa(s,i,e,t){if(_e(s))for(let r=0;r<s.length;r++)Ta.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Ta.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function Ta({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:V.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(g(i)){if(s.required)throw new L(o(5001));if(g(s.defaultValue)){ie(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let d=0;d<s.type.length;d++)s.type[d]===null&&i===null&&(c=!0),ie(s.type[d])&&i instanceof s.type[d]&&(c=!0),Y(s.type[d])&&Ae(i)===s.type[d].toLowerCase()&&(c=!0);if(!c)throw new L({code:V.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(d=>Zs(d)?yn(d):Y(d)?d:Ae(d))},value:i}})}else if(!g(s.type)&&Ae(i)!==s.type)throw new L(o(5002));if(s.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new L(o(5003))}if(s.notLessThanZero&&ee(i)&&i<0)throw new L(o(5006));if(!g(s.min)&&ee(i)&&i<s.min)throw new L(o(5007));if(!g(s.max)&&ee(i)&&i>s.max)throw new L(o(5008));if(Y(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new L(o(5004))}else if(ie(s.instanceOf)&&!(i instanceof s.instanceOf))throw new L(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new L(o(5005));let{properties:n}=s;Ze(n)&&yt(i)&&Object.keys(n).forEach(c=>{Ta.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Ze(a)&&_e(i)&&i.forEach((c,d)=>{Ta.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:r})}),ie(s.validate)&&s.validate.call(this,i,e,t,r,this)}function ae(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=s;return j((r,o)=>function(...n){var l;function a(m,p,_){if(_&&_.includes(m))return"hided";if(e){let I=e(...n);if(n[I.argIndex]===p)return I.value}if(p===n||m in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${Ae(p)}`:(JSON.stringify(p),p)}catch(I){return`type:${Ae(p)}`}}let c=this._log||y;n.length>0?c.info(`${o}() ${JSON.stringify(n,(m,p)=>a(m,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):Mn[o];try{let m=r.apply(this,n),p=P();return or(m)?m.then(_=>(c.info(`${o}() success ${i.call(this,...n)}`),v.addSuccessEvent({key:d,cost:P()-p}),_)).catch(_=>{var C;_=L.convertFrom.call(this,_,o,n.length===1?n[0]:n);let I=_.extraCode||_.code,A=(C=_.message)!=null&&C.includes(I)?"":` code:${I}`;throw c.error(`${o}() failed ${i.call(this,...n)} ${_}${A} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:_}),_}):(v.addSuccessEvent({key:d}),m)}catch(m){m=L.convertFrom.call(this,m,o);let p=m.extraCode||m.code,_=(l=m.message)!=null&&l.includes(p)?"":` code:${p}`;throw c.error(`${o}() failed ${m}${_} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:m}),m}})}var Ia=s=>j((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new L({code:V.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ie(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new L({code:V.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Sa.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Aa=0,iu=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new ts(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function hs(s,i){if(i&&typeof i!="function")throw new L({code:V.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ms=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Aa=Aa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Aa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Aa}`),this.core=i}getName(){return ms.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ms.startValidateRule;case"update":return ms.updateValidateRule;case"stop":return ms.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new iu(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),g(t)||n.setOperation(t),g(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),r&&v.addCount({key:502704}),o&&v.addCount({key:502705}),n&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof c!="function"&&v.addCount({key:502709}),typeof l!="function"&&v.addCount({key:502710}),typeof d!="function"&&v.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Qi=ms;u(Qi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),d=r.startsWith("data");if(!(a||c||d))throw new L({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new L({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});hs("onTimeUpdate",i.onTimeUpdate),hs("onEnded",i.onEnded),hs("onDurationChange",i.onDurationChange)}}),u(Qi,"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){hs("onTimeUpdate",i.onTimeUpdate),hs("onEnded",i.onEnded),hs("onDurationChange",i.onDurationChange)}}),u(Qi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Qi,"Name","AudioMixer");var y_=s=>(s=Number(s),s>0&&s<14e8),Ca=0,ru,ps=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",ve("denoiser"));u(this,"workletNode");Ca=Ca+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ca}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ca}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new L({code:V.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return ru||(ru=this.doPreload(i)),ru}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield dr(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return ps.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return ps.startValidateRule(this.core);case"update":return ps.updateValidateRule;case"stop":return ps.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield N_(x(D({},i),{timestamp:t}));if(!r)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${r}. Message: ${a}`),new L({code:V.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},Ir=ps;u(Ir,"updateValidateRule",{type:"object"}),u(Ir,"stopValidateRule",{type:"object"}),u(Ir,"Name","AIDenoiser");var Uh={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function b_(s){let i;return y_(s)?i=Uh.MAIN_OVERSEA:i=Uh.MAIN,i}function N_(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`https://${b_(s)}/api/v1/audioAiAuth?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var Vh=ye(xe(),1);var su=class extends Vh.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){K.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)&&y.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){K.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},v_=new su,ou=v_;function nu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ii(new DataView(new Uint8Array(o).buffer),!0)}function au(s){return s.type==="empty"||s.data.byteLength===0}function cu(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function du(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function uu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let e=du(s.data),t=9-e;if(t<=0)return s;let r=i.splice(0,t).reverse().map(nu),o=r.reduce((l,m)=>l+m.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),d=0;for(let l=0;l<r.length;l++)for(let m=0;m<r[l].dataView.byteLength;m++)a.setInt8(d++,r[l].dataView.getInt8(m));for(let l=0;l<s.data.byteLength;l++)a.setInt8(d++,c.getInt8(l));return s.data=n,s}function lu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(au(s)||!cu(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let d=a-r;if(o===-1?o=d:n===-1&&(n=d,t.push(new Ii(new DataView(e.buffer.slice(o,n)))),o=d,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(d);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var hu=0,mu=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);hu++,this.log=i.log.createChild({id:`${this.getAlias()}${hu}`}),this.log.info(`[sei] created id=${this.getAlias()}${hu}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return uu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return lu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:vt?this.encode:uu,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:vt?this.decode:lu,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return mu.Name}getAlias(){return"sei"}getGroup(){return"sei"}},fs=mu;u(fs,"autoStart",!0),u(fs,"Name","SEI");var D_=0,Ra,pu=class{constructor(i){this.core=i;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++D_}`}),this.log.info("created")}getName(){return pu.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*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){try{if(Ra)yield Ra;else{let i=Date.now();Ra=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Ie}.js`),yield Ra,this.log.info(`download debug dialog script cost: ${Date.now()-i}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo({frame:i,mediaType:e}){return this.encodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return this.decodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}encodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}decodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}},Ar=pu;u(Ar,"Name","Debug"),u(Ar,"autoStart",!0),N([je({settings:{timeout:3e3,retries:3},onError(s,i,e){var t;(t=s==null?void 0:s.message)!=null&&t.includes("timeout")?i():e(s)}})],Ar.prototype,"loadScript",1);var Bh=0,ya=new Set,Oe=null;Fa(wh);var O_={RtcError:L,ErrorCode:V,ErrorCodeDictionary:Mt},lt=class extends $h.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",y.createLogger({id:`t${++Bh}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"_getPCMAbortCtrl");this._room=new e(D({logger:this._log,frameWorkType:lt.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Qi,t.assetsPath),this._use(Ir,t.assetsPath),this._use(Ar),t.enableSEI&&lo&&this._use(fs),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.enableDbVolume&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.volumeDb)}),this.emit(M.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new L({code:V.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Lh(this,"trtc")}static create(e){}static _create(e,t){Ch();let r=new lt(e,t||{});return ya.add(r),r}get room(){return this._room}_listenEvents(){Ue(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,L.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=x(D({},e),{uplinkRTT:Math.min(e.uplinkRTT,Ls),downlinkRTT:Math.min(e.downlinkRTT,Ls)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ue(r,r).add("player-state-changed",o=>{let n=x(D({},o),{userId:e.userId});r.kind===h.VIDEO&&(n.streamType=Oo(r.streamType)),this.emit(r.kind===h.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:r.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ee(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._remoteVideoConfigMap.delete(`${r}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${r}_${"sub"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t})),n!==c&&(T.emit(c?"254":"255",{userId:r,streamType:"main",room:this.room}),this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,x(D({},e),{streamType:Oo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new L({code:V.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Ls),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/at},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/at},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(M.STATISTICS,r)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}).add("ntp-time-updated",()=>{this.emit(M.NETWORK_TIME_UPDATED,{networkTime:ot()})}),Ue(this,ge).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===ks){let t=(yield Wi()).find(r=>r.deviceId===ks);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Wi())[0];if(!t||!Oe||Oe.groupId===t.groupId)return;let r=Oe.deviceId===e.deviceId,o=Oe.deviceId===ks&&Oe.deviceId===t.deviceId;(r||o)&&(Oe=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}getNetworkTime(){return ot()}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||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let o=new e(Ph.call(this,{TRTC:lt,room:this._room,errorModule:O_,assetsPath:t}));return this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name),o}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,le(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,lt.frameWorkType),this._checkTrackToPublish(),ou.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Ee(this),this.removeAllListeners(),this._room.destroy(),ya.delete(this),ya.size===0&&ou.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new Me(this._room.audioManager),a={},c={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(Y(o.profile)?zo[o.profile]&&n.setProfile(zo[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),g(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),g(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),g(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit(M.ERROR,new L({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let l;d.error&&(l=L.convertFrom(d.error)),this.emit(M.PUBLISH_STATE_CHANGED,x(D({},d),{error:l}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(r)||n.setMute(r),Ue(n,n).add("player-state-changed",d=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,x(D({},d),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(lt.EVENT.AUDIO_FRAME,{data:d})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(lt.EVENT.AUDIO_FRAME,{data:d})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=x(D({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):g(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),g(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),g(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),pi(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Ee(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new me(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(n.profile)||(Y(n.profile)?nt[n.profile]&&a.setProfile(nt[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),g(n.small)||(ao()?Y(n.small)?a.small=nt[n.small]:n.small===!0?a.small=nt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit(M.ERROR,new L({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=L.convertFrom(l.error)),this.emit(M.PUBLISH_STATE_CHANGED,x(D({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let l=Sr(n.qosPreference);a.mediaTrack.contentHint=l}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=Sr(fr.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}Ue(a,a).add("player-state-changed",l=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,x(D({},l),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=x(D({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n){if(g(n.profile)||(Y(n.profile)?nt[n.profile]&&this._localVideoTrack.setProfile(nt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):g(n.useFrontCamera)?g(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=Sr(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=c)}if(n.small){let c=!this._localVideoTrack.small;ao()?(n.small===!0?this._localVideoTrack.small=nt["120p"]:Y(n.small)?this._localVideoTrack.small=nt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),pi(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(),Ee(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new rt(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=L.convertFrom(m.error)),this.emit(M.PUBLISH_STATE_CHANGED,x(D({},m),{error:p}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},d={};o&&(g(o.profile)||(Y(o.profile)?Yo[o.profile]&&n.setProfile(Yo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),g(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let l=yield n.capture(c);if(o!=null&&o.qosPreference){let m=Sr(o.qosPreference);n.mediaTrack.contentHint=m}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=Sr(fr.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new Yt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Ue(n,n).add("player-state-changed",m=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,x(D({},m),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let m=[n];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=x(D({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=Sr(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),pi(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let d={},l=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),n&&!g(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var C,F;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let d={};n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror));let l=null,m=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),o==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:p}=c;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:p}),pi(p,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(C=p.option)==null?void 0:C.receiveWhenViewVisible:n.receiveWhenViewVisible,I=g(t)?p.view:t,A=g(n==null?void 0:n.viewRoot)?(F=p.option)==null?void 0:F.viewRoot:n.viewRoot;this._observeView({remoteTrack:l,view:I,receiveWhenViewVisible:_,viewRoot:A})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&r.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&r.push(d))}for(let a of r)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===lt.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(lt.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(lt.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{Mh.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===lt.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(Y(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Wi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Oe=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t,option:r}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};r&&(g(r.volume)||(n.volume=r.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.get(r.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),g(e)&&o&&o.view&&!vc(t)){let a=to(o.view);a.length>0&&(yield r.play(a,t))}if(!g(e)){let a=to(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(M.TRACK,{userId:r,streamType:Oo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,r,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((r=this._localVideoConfig)==null?void 0:r.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Oo(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||_e(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,l=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(to(t));d.forEach((p,_)=>{m.has(_)||(a.unobserve(_),d.delete(_))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{Ee(e.remoteAudioTrack),Ee(e.remoteVideoTrack),Ee(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Ee(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(Oe&&!rs(Oe))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield Wi();if(e[0]&&!rs(e[0]))Oe=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:r})=>{r.kind==="audio"&&(!Oe||rs(Oe))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:x(D({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.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})}static setLogLevel(e,t){y.setLogLevel(e),g(t)||(t?y.enableUploadLog():y.disableUploadLog())}static isSupported(){return wn()}static getCameraList(e=!0){return tt(e)}static getMicrophoneList(e=!0){return qe(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Wi()).forEach(r=>{r.deviceId===e&&(ya.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Oe=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(ar.version=a),e){case"count":ar.addCount({key:t,useUV:n});break;case"enum":ar.addEnum({key:t,value:r,useUV:n});break;case"number":ar.addNumber({key:t,value:r,split:o});break}}},Q=lt;u(Q,"_loggerManager",y),u(Q,"EVENT",M),u(Q,"ERROR_CODE",V),u(Q,"TYPE",fr),u(Q,"frameWorkType",30),N([ae({replaceArg:s=>({argIndex:0,value:{name:"plugin"in s?s.plugin.Name:s.Name,assetsPath:"assetsPath"in s?s==null?void 0:s.assetsPath:"default"}})})],Q.prototype,"use",1),N([Be(De.TRTC.enterRoom),qi("room",([s],[i])=>(s.roomId||s.strRoomId)===(i.roomId||i.strRoomId)&&s.userId===i.userId&&s.sdkAppId===i.sdkAppId),j(s=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),s.call(this,i)}),ae()],Q.prototype,"enterRoom",1),N([ae()],Q.prototype,"exitRoom",1),N([Be(De.TRTC.switchRole),Tr("room",{merge:(s,i)=>i}),ae()],Q.prototype,"switchRole",1),N([ae()],Q.prototype,"destroy",1),N([Be(De.TRTC.startLocalAudio),qi("audio",([s],[i])=>{var e,t;return((e=s==null?void 0:s.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ae()],Q.prototype,"startLocalAudio",1),N([Be(De.TRTC.updateLocalAudio),Tr("audio",{debounce:{delay:200,getKey:()=>`${Bh}-localAudio`,isNeedToDebounce:s=>{var i;return!g((i=s.option)==null?void 0:i.captureVolume)}}}),ae()],Q.prototype,"updateLocalAudio",1),N([Xi("audio"),ae()],Q.prototype,"stopLocalAudio",1),N([Be(De.TRTC.startLocalVideo),qi("video",([s],[i])=>{var e,t;return((e=s==null?void 0:s.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ae()],Q.prototype,"startLocalVideo",1),N([Be(De.TRTC.updateLocalVideo),Tr("video"),ae()],Q.prototype,"updateLocalVideo",1),N([Xi("video"),ae()],Q.prototype,"stopLocalVideo",1),N([Be(De.TRTC.startScreenShare),qi("screen",()=>!0),ae()],Q.prototype,"startScreenShare",1),N([Be(De.TRTC.updateScreenShare),Tr("screen"),ae()],Q.prototype,"updateScreenShare",1),N([ae()],Q.prototype,"stopScreenShare",1),N([Be(De.TRTC.startRemoteVideo),qi(s=>`v${s.userId}${s.streamType}`,()=>!0),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],Q.prototype,"startRemoteVideo",1),N([Be(De.TRTC.updateRemoteVideo),Tr(s=>`v${s.userId}${s.streamType}`),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],Q.prototype,"updateRemoteVideo",1),N([Be(De.TRTC.stopRemoteVideo),j(s=>function(i){return f(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return s.call(this,i)})}),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],Q.prototype,"stopRemoteVideo",1),N([Xi(s=>`v${s.userId}${s.streamType}`)],Q.prototype,"_stopRemoteVideo",1),N([Be(...De.TRTC.muteRemoteAudio),ae({getRemoteId:s=>s})],Q.prototype,"muteRemoteAudio",1),N([tu(...De.TRTC.setRemoteAudioVolume),xh(200,s=>s),ae({getRemoteId:s=>s})],Q.prototype,"setRemoteAudioVolume",1),N([Ia("start"),Dt(s=>{var i;return(i=s.afterStart)==null?void 0:i.call(s)}),qi((s,i)=>s.disableRandomCall?null:s.getAlias()+s.getGroup(i)),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Bc[s.getName()]})],Q.prototype,"startPlugin",1),N([Ia("update"),Tr((s,i)=>s.disableRandomCall?null:s.getAlias()+s.getGroup(i)),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>$c[s.getName()]})],Q.prototype,"updatePlugin",1),N([Ia("stop"),Xi((s,i)=>{if(s.disableRandomCall)return null;let e=s.getGroup(i),t=s.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Fc[s.getName()]})],Q.prototype,"stopPlugin",1),N([tu(...De.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),N([ae()],Q.prototype,"getVideoSnapshot",1),N([ae()],Q.prototype,"_setCurrentSpeaker",1),N([qi(s=>`a${s.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),N([j(s=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(x(D({},i),{userId:e.userId})).catch(()=>{}))):s.call(this,i)})}),Xi(s=>`a${s.userId}`)],Q.prototype,"_stopRemoteAudio",1),N([Xi("room")],Q.prototype,"_exitRoom",1),N([Xi("screen")],Q.prototype,"_stopScreenShare",1),N([Be(...De.TRTC.sendSEIMessage),Zd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...s)=>s[0].byteLength})],Q.prototype,"sendSEIMessage",1),N([Be(De.TRTC.sendCustomMessage),Zd({timesInSecond:30,maxSizeInSecond:8e3,getSize:s=>s.data.byteLength})],Q.prototype,"sendCustomMessage",1),N([Be(De.TRTC.create)],Q,"_create",1);var Mo=Q;var fu=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function M_(){return f(this,null,function*(){let s,i;try{let m=yield qe();s=m&&m.length}catch(m){}try{let m=yield tt();i=m&&m.length}catch(m){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Wt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};K.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),K.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Fh(){return j(s=>{let i=new fu;return function(e,t,r){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:S.INVALID_OPERATION,message:U({key:w.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:S.INVALID_OPERATION,message:U({key:w.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:o,params:e});let n=Fe.getEnv();n||(n=ri.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ko.OLD_CLOUD_LADDER)?n=ri.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ko.WEBRTC)&&(n=ri.WEBRTC))),K.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Wt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,M_.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Fe.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Fe.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&K.uploadEvent({log:`stat-conv-${Number(di)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(E.JOIN_FAILED,{room:this,error:a}),a}})}})}var Hh=()=>j(s=>function(...i){return f(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield s.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Gh(){return j(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Jh=ye(xe());var pe={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var ht={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,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},Wh=[ht.UPDATE_REMOTE_MUTE_STAT,ht.UPLINK_NETWORK_STATS,ht.USER_LIST_RES,ht.MUTE_RESULT,ht.SERVER_FIRST_PACKAGE_RECEIVED,ht.RECEIVE_CUSTOM_MSG,ht.UPDATE_NETWORK_TIME_RESULT],B={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",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",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",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",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var ba=new Set;function jh(s){let i=[...ba.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var _s=class extends Jh.default{constructor(e){var r,o;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");u(this,"stopKeepAliveTimeout");u(this,"rtt",0);this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0)-ba.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ba.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=y.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=P();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 Ys(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?h.MAIN:h.BACKUP),c(new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse){if(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}this.room.isJoining&&this.emit(pe.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"}))}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(pe.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=bn(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(ht),c=Object.keys(ht)[n.indexOf(r)],d=B[c]||r;switch(Wh.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),r){case ht.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:P()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(pe.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:U({key:w.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:l}),this.emit(pe.SETUP_FAILED,l)}break}case ht.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;$t(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:B.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:P()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=bn(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((d,l)=>{let m=setTimeout(()=>{this.off(o,p);let I=new b({code:S.API_CALL_TIMEOUT,message:U({key:w.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(I),l(I)},r),p=I=>{I.data.seq===_&&(clearTimeout(m),this.off(o,p),c&&(I.data.receiveTime=Date.now()),d(I))};this.on(o,p);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Bt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(pe.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),ba.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(B.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(B.JOIN_ROOM_RESULT,t))};this.on(B.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(pe.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(pe.CONNECTED):e==="DISCONNECTED"&&this.emit(pe.DISCONNECTED))}};N([je({settings:{retries:1/0,timeout:2e3},onError(s,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(s,i){this._log.warn(`retrying to connect ${s}`),s>=3&&s%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],_s.prototype,"connect",1);var qh=ye(xe());var _u=0,Eu=!1,Na=new Set,P_=s=>_u>2&&!Eu&&Na.size===0&&s,gu=!1,He=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new qh.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=y.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=P())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(P()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:P()-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(),Na.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new b({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ft;let i=null;if(this._isUplink){if(!Gi()||this._peerConnection.getSenders().length===0)return ft;i=this._peerConnection.getSenders()[0].transport}else{if(!cr()||this._peerConnection.getReceivers().length===0)return ft;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ft}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===ne.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ne.FAILED||i.target.connectionState===ne.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===ne.CONNECTED||i.target.connectionState===ne.COMPLETED)&&(this.logSelectedCandidate(),K.logSuccessEvent({userId:this._room.userId,eventType:Ge.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(_u=0,Eu=!1,gu=!0,Na.add(this)):Na.delete(this),T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Hi(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:S.API_CALL_ABORTED,message:U({key:w.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(E.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});_u+=1,P_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Eu=!0,this._emitter.emit("firewall-restriction")),e(a)},Ms);T.on(E.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(pe.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=si()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:U({key:this._isUplink?w.UPLINK_RECONNECTION_FAILED:w.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(pe.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)}};N([Xe(521712,!1)],He.prototype,"setOffer",1),N([Xe(521713,!1)],He.prototype,"setAnswer",1);var Au=ye(Iu());var ue=function(s){return Au.default.parse(s)},mt=function(s){return Au.default.write(s)},tm=function(s){let i=ue(s);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),mt(i)};function im(s){let i=ue(s);return i.media.forEach(e=>{var t,r;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),mt(i)}function va(s){return Object.keys(s).filter(i=>s[i])}var Ru=class extends He{constructor(e){super(x(D({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"isRobot",!1);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ai(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ot(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ds(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return $i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===Os?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=h.AUDIO;r.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
55
|
+
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
56
|
+
`)}addSPSDescription(e){let t=ue(e);return t.media.forEach(r=>{r.type===h.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),mt(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=ue(e);return r.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),mt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===ne.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===ne.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=D({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${va(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:U({key:w.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,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:B.SUBSCRIBE_RESULT,timeout:Ya});if(!this._peerConnection){let a=new b({code:S.INVALID_OPERATION,message:U({key:w.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};ct()&&this._sdpSemantics===Oi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield xn();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=im(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=tm(t.sdp),this._sdpSemantics===Oi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Zi)throw new b({code:S.NOT_SUPPORTED_H264,message:U({key:w.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:U({key:w.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ue(e).media.forEach(r=>{if(!!r.ssrcs)if(r.type===h.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Os)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Os)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ja)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(Se(Ru.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=Ft(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}setAudioJitterBuffer(e){if(!this._peerConnection)return;let t=this._peerConnection.getReceivers()[0];!t||(this._log.warn(`setAudioJitterBuffer ${e}`),t.jitterBufferTarget=e)}},gs=Ru;N([j(s=>function(...i){return new Promise((e,t)=>{let r=o=>{this._emitter.off("closed",r),t(new b({code:S.API_CALL_ABORTED,message:U({key:w.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",r),s.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",r)})})})],gs.prototype,"subscribe",1),N([Xe(521717,!1)],gs.prototype,"unsubscribe",1),N([Dt(He.prototype.afterConnect),zn(He.prototype.beforeConnect)],gs.prototype,"connect",1);var Cu=gs;var sm={voiceActivityDetection:!1},yu=class extends He{constructor(e){super(x(D({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Ht()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return 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(),ct()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:z.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let p=o?3:1;yield l[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),m.push(p),r&&(yield l[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(z.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack: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 d=new MediaStream;d.addTrack(r),this._peerConnection.addTrack(r,d)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(z.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Ht()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=x(D({},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=x(D({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(z.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Gt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),ct()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===z.INACTIVE&&(yield this.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Ht()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof me&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Or||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ue(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;Ht()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ie(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),ct()?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===h.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!se)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(d=>{n[d].direction!==e&&(n[d].direction=e,r=!0)}),r){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this.setOffer(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
57
|
+
`).map(d=>{if(d.match(new RegExp(`a=(${z.INACTIVE}|${z.RECVONLY}|${z.SENDONLY})`))&&a++,t.includes(a)){if(e===z.INACTIVE&&d.includes(`a=${z.RECVONLY}`))return o=!0,`a=${e}`;if(e===z.SENDONLY&&d.includes(`a=${z.INACTIVE}`))return o=!0,`a=${z.RECVONLY}`}return d}).join(`\r
|
|
58
|
+
`);o&&(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===h.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===h.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===h.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(ct()?r=e.kind===h.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(sm);se&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_CHANGE,data:n,responseCommand:B.UPDATE_OFFER_RESULT,timeout:za,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:o}){if(!uo())return o?t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e):void 0;let a,c=this._peerConnection.getSenders();if(ct()){let d=0;t===h.VIDEO&&(r===h.SMALL?d=2:r===h.AUXILIARY?d=3:d=1),a=c[d]}else a=c.find(d=>d.track&&d.track.kind===t);if(a){let d=a.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(d),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),o}catch(l){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${l}`),o)return t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,r){let o="AS";se&&(o="TIAS",t=t*1e3);let n=0,a=-1;return r===h.SMALL?n=1:r===h.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${o}:${t}\r
|
|
59
|
+
`:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return se&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
60
60
|
c=IN $2\r
|
|
61
|
-
b=${
|
|
62
|
-
`),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(nm);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:W.PUBLISH,responseCommand:B.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof st||this.localAuxVideoTrack instanceof st,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:o,data:n}=t.data;return s===0?this.acceptAnswer(n):this.checkPublishResultCode(s,o)})}setSDPDirection(e,t,s="all"){let o=ue(e);return o.media.forEach(n=>{(s==="all"||n.type===s)&&(n.direction=t)}),mt(o)}acceptAnswer(e){return f(this,null,function*(){var t,s,o,n,a;try{let d;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),p=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let _=this._isPublishingAux?h.AUXILIARY:h.BIG;d=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:d,videoType:_})}p&&(d=yield this.setBandwidth({bandwidth:p,type:h.AUDIO,sdp:d}))}if(d=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:m}=this._room;d=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||m.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:d})}let l={type:e.type,sdp:d};yield this.setAnswer(l),this._log.debug(`accepted answer: ${d}`)}catch(d){throw this._log.error(`failed to accept remote answer ${d}`),d}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(W.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(ye(Cu.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,responseCommand:B.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=Ht(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(g.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ue(e).media.forEach((s,o)=>{if(s.type===h.AUDIO){let n=s.ssrcs&&s.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Or&&s.ssrcGroups){s.ssrcGroups.forEach((a,d)=>{let c=Number(a.ssrcs.split(" ")[0]);d===0?this.ssrc.video=c:d===1&&(this.ssrc.small=c)});return}let n=s.ssrcs&&s.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===tr?(this._log.error(Ne.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:U({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.PUBLISH_RESULT,code:e,message:t}})})}},Ts=Cu;N([j(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],Ts.prototype,"publish",1),N([Qe(521715,!1)],Ts.prototype,"unpublish",1),N([Ot(Ge.prototype.afterConnect),Qn(Ge.prototype.beforeConnect)],Ts.prototype,"connect",1);var ko=Ts;var Po=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime",0);u(this,"_prevReport",{});u(this,"_prevStats",null);u(this,"_prevEncoderImplementation","");u(this,"_prevAuxEncoderImpl","");u(this,"_prevQualityLimitationReason","");u(this,"_prevAuxQualityLimitationReason","");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var l,m,p;let d,c;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===h.VIDEO){if(a.ssrc===s.video?(d=h.VIDEO,c=i.localMainVideoTrack):a.ssrc===s.small?d=h.SMALL:a.ssrc===s.auxiliary&&(c=i.localAuxVideoTrack,d=h.AUXILIARY),!d)return;if(e[d].bytesSent=a.bytesSent,e[d].packetsSent=a.packetsSent,e[d].framesEncoded=a.framesEncoded,E(a.keyFramesEncoded)||(e[d].keyFramesEncoded=a.keyFramesEncoded),E(a.nackCount)||(e[d].nackCount=a.nackCount),E(a.pliCount)||(e[d].pliCount=a.pliCount),E(a.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=a.retransmittedPacketsSent),E(a.totalEncodeTime)||(e[d].totalEncodeTime=a.totalEncodeTime),E(a.totalPacketSendDelay)||(e[d].totalPacketSendDelay=a.totalPacketSendDelay),!E(a.encoderImplementation)&&(d===h.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||d===h.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let I=2,A=this._prevEncoderImplementation;d===h.AUXILIARY&&(I=7,A=this._prevAuxEncoderImpl),T.emit("262",{userId:i.userId,streamType:I,prevImplementation:A,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[d===h.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${d===h.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===s.video?!E(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(l=i.localMainVideoTrack)==null?void 0:l.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===s.auxiliary&&!E(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(m=i.localAuxVideoTrack)==null?void 0:m.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?Wi(a)&&(this.totalBytesSent=a.bytesSent,te(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===h.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===h.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!E(a.audioLevel)&&((p=i.localMainAudioTrack)==null?void 0:p.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!E(a.frameWidth)){let _=h.SMALL;a.trackIdentifier===i.getVideoTrackId(h.VIDEO)||a.ssrc===s.video?_=h.VIDEO:(a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||a.ssrc===s.auxiliary)&&(_=h.AUXILIARY),e[_].frameWidth=a.frameWidth,e[_].frameHeight=a.frameHeight,e[_].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===h.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===h.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===h.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var s;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:o}=i,{muteState:n,subscribeState:a}=i;(this._spcStats||(yield t.getStats())).forEach(c=>{if(c.type==="inbound-rtp"){let l=(c.mediaType||c.kind)===h.AUDIO;if(l){if(c.ssrc!==o.audio||!n.hasAudio)return;e.audio.packetsReceived=c.packetsReceived,e.audio.bytesReceived=c.bytesReceived,e.audio.packetsLost=c.packetsLost,c.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=c.insertedSamplesForDeceleration),c.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=c.removedSamplesForAcceleration),c.totalSamplesDuration&&(e.audio.totalSamplesDuration=c.totalSamplesDuration),c.totalSamplesReceived&&(e.audio.totalSamplesReceived=c.totalSamplesReceived),c.concealedSamples&&(e.audio.concealedSamples=c.concealedSamples);let{remoteAudioTrack:m}=i;m.stat.packetsReceived=c.packetsReceived,m.stat.bytesReceived=c.bytesReceived,m.stat.packetsLost=c.packetsLost,e.audio.p2pDelay=m.stat.end2EndDelay,e.hasAudio=!0}else{if(se&&c.bytesReceived===0)return;let m;c.ssrc===o.video&&n.hasVideo&&(e.video.packetsReceived=c.packetsReceived,e.video.bytesReceived=c.bytesReceived,e.video.packetsLost=c.packetsLost,e.video.framesReceived=c.framesReceived,e.video.framesDecoded=c.framesDecoded,e.video.fpsDecoded=c.framesPerSecond,e.hasVideo=!0,m=i.remoteVideoTrack,n.hasSmall&&a.smallVideo&&(e.isSmallSubscribed=!0),c.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==c.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${c.decoderImplementation} HWDecoder: ${c.powerEfficientDecoder}`),T.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:c.decoderImplementation,codec:i.videoCodec,isHWCodec:c.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,c.decoderImplementation))),c.ssrc===o.auxiliary&&n.hasAuxiliary&&(e.auxiliary.packetsReceived=c.packetsReceived,e.auxiliary.bytesReceived=c.bytesReceived,e.auxiliary.packetsLost=c.packetsLost,e.auxiliary.framesReceived=c.framesReceived,e.auxiliary.framesDecoded=c.framesDecoded,e.auxiliary.fpsDecoded=c.framesPerSecond,m=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),m&&(m.stat.packetsReceived=c.packetsReceived,m.stat.bytesReceived=c.bytesReceived,m.stat.packetsLost=c.packetsLost,m.stat.framesReceived=c.framesReceived,m.stat.framesDecoded=c.framesDecoded,c.jitterBufferDelay&&(m.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)))}c.jitterBufferDelay&&(l?(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===o.video&&n.hasVideo?(e.video.totalJitter=c.jitterBufferDelay,e.video.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===o.auxiliary&&n.hasAuxiliary&&(e.auxiliary.totalJitter=c.jitterBufferDelay,e.auxiliary.totalJitterCount=c.jitterBufferEmittedCount))}else c.type==="candidate-pair"&&Wi(c)&&(this.totalBytesReceived=c.bytesReceived,te(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3)));E(c.frameWidth)||((c.trackIdentifier===i.getMainStreamVideoTrackId()||c.ssrc===o.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,i.remoteVideoTrack.stat.frameWidth=c.frameWidth,i.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===i.getAuxStreamVideoTrackId()||c.ssrc===o.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=c.frameHeight)),!E(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(o){this._log.warn(`failed to getStats on receiver connection ${o}`)}return e.rtt===0&&(e.rtt=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},s=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:s};let n=P(),a=yield o.getStats(),d=P();d-n>2e3&&this._log.warn(`getStats cost ${d-n}ms`);let c=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(m=>l.has(m.type)&&c.push(m)),this._spcStats=c}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(zt(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m;if(!zt(i.senderStats)){let p={uint32_audio_level:i.senderStats.audio.audioLevel*at,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(p.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*at),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let _=[];if(i.senderStats.video.bytesSent){let A={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};_.push(A)}if(i.senderStats.small.bytesSent){let A={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};_.push(A)}if(i.senderStats.auxiliary.bytesSent){let A={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};_.push(A)}let I={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:p,msg_video_status:_,msg_network_status:I}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(p=>{let _={msg_user_info:{str_identifier:p.userId,uint64_tinyid:p.tinyId},msg_network_status:{uint32_rtt:p.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(p.hasAudio){let I={uint32_audio_p2p_delay:p.audio.p2pDelay,uint32_audio_cache_ms:p.audio.totalJitter,uint32_audio_cache_ms_count:p.audio.totalJitterCount,uint32_audio_codec_bitrate:p.audio.bytesReceived,uint32_audio_total_bitrate:p.audio.bytesReceived,uint32_audio_level:p.audio.audioLevel*1e8,uint32_audio_energy:p.audio.totalAudioEnergy*1e6,uint32_audio_receive:p.audio.packetsReceived,uint32_audio_origin_lost:p.audio.packetsLost};_.msg_audio_status=I}if(p.hasVideo){let I=t.get(`${p.userId}_${qa}`),A=I?I.duration:0,R={uint32_video_stream_type:p.isSmallSubscribed?3:2,uint32_video_receive_fps:p.video.framesReceived,uint32_video_width:p.video.frameWidth,uint32_video_height:p.video.frameHeight,uint32_video_codec_bitrate:p.video.bytesReceived,uint32_video_receive:p.video.packetsReceived,uint32_video_origin_lost:p.video.packetsLost,uint32_video_block_time:A,uint32_video_dec_fps:p.video.framesDecoded,uint32_video_cache_ms:p.video.totalJitter,uint32_video_cache_ms_count:p.video.totalJitterCount};_.msg_video_status.push(R)}if(p.hasAuxiliary){let I=t.get(`${p.userId}_${Xa}`),A=I?I.duration:0,R={uint32_video_stream_type:7,uint32_video_receive_fps:p.auxiliary.framesReceived,uint32_video_width:p.auxiliary.frameWidth,uint32_video_height:p.auxiliary.frameHeight,uint32_video_codec_bitrate:p.auxiliary.bytesReceived,uint32_video_receive:p.auxiliary.packetsReceived+p.auxiliary.packetsLost,uint32_video_origin_lost:p.auxiliary.packetsLost,uint32_video_block_time:A,uint32_video_dec_fps:p.auxiliary.framesDecoded,uint32_video_cache_ms:p.auxiliary.totalJitter,uint32_video_cache_ms_count:p.auxiliary.totalJitterCount};_.msg_video_status.push(R)}e.msg_down_stream_info.push(_)});let o=this._prevReport,n=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let p=o.msg_up_stream_info.msg_audio_status,_=e.msg_up_stream_info.msg_audio_status;if(p.uint32_audio_codec_bitrate===0)_.uint32_audio_codec_bitrate=0;else{let I=this.getDifferenceValue(p.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(I*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_audio_codec_bitrate}(m=o.msg_device_info)!=null&&m.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s):delete e.msg_device_info.uint32_audio_capture_cost}let a=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(p=>{let _=a.find(Me=>Me.uint32_video_stream_type===p.uint32_video_stream_type);if(!_||_.uint32_video_codec_bitrate===0){p.uint32_video_codec_bitrate=0,p.uint32_video_enc_fps=0,p.uint32_video_codec_fps=0;return}let I=0,A=0,R=0;_&&p.uint32_video_codec_bitrate>=_.uint32_video_codec_bitrate&&(I=_.uint32_video_codec_bitrate,A=_.uint32_video_enc_fps,R=_.uint32_video_codec_fps);let $=this.getDifferenceValue(I,p.uint32_video_codec_bitrate);p.uint32_video_codec_bitrate=Math.round($*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=p.uint32_video_codec_bitrate,p.uint32_video_enc_fps=Math.round(this.getDifferenceValue(A,p.uint32_video_enc_fps)/s),p.uint32_video_codec_fps=Math.round(this.getDifferenceValue(R,p.uint32_video_codec_fps)/s),At&&ci()===115&&_.uint32_video_width===0&&_.uint32_video_height===0&&_.uint32_video_codec_fps===0&&(p.uint32_video_codec_fps=p.uint32_video_enc_fps),E(_.uint32_key_frame_count)||(p.uint32_key_frame_count=Math.round(this.getDifferenceValue(_.uint32_key_frame_count,p.uint32_key_frame_count))),E(_.uint32_nack_count)||(p.uint32_nack_count=Math.round(this.getDifferenceValue(_.uint32_nack_count,p.uint32_nack_count))),E(_.uint32_pli_count)||(p.uint32_pli_count=Math.round(this.getDifferenceValue(_.uint32_pli_count,p.uint32_pli_count))),E(_.uint32_video_arq_packets)||(p.uint32_video_arq_packets=Math.round(this.getDifferenceValue(_.uint32_video_arq_packets,p.uint32_video_arq_packets))),E(_.uint32_encode_cost)||(p.uint32_encode_cost=Math.round(this.getDifferenceValue(_.uint32_encode_cost,p.uint32_encode_cost)/s)),E(_.uint32_send_packet_cost)||(p.uint32_send_packet_cost=Math.round(this.getDifferenceValue(_.uint32_send_packet_cost,p.uint32_send_packet_cost)/s))});let c=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(p=>c.find(_=>_.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid));let l=e.msg_down_stream_info;return l.forEach(p=>{let _=c.find(I=>I.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid);if(!zt(p.msg_audio_status)&&!zt(_.msg_audio_status)){let I=p.msg_audio_status,A=_.msg_audio_status,R=this.getDifferenceValue(A.uint32_audio_cache_ms_count,I.uint32_audio_cache_ms_count);delete I.uint32_audio_cache_ms_count,I.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(A.uint32_audio_cache_ms,I.uint32_audio_cache_ms)/R)||0;let $=this.room.remotePublishedUserMap.get(p.msg_user_info.str_identifier);$&&($.remoteAudioTrack.stat.jitterBufferDelay=I.uint32_audio_cache_ms),I.uint32_audio_origin_lost=this.getDifferenceValue(A.uint32_audio_origin_lost,I.uint32_audio_origin_lost),I.uint32_audio_receive=this.getDifferenceValue(A.uint32_audio_receive,I.uint32_audio_receive),I.uint32_audio_receive+=I.uint32_audio_origin_lost;let Me=this.getDifferenceValue(A.uint32_audio_codec_bitrate,I.uint32_audio_codec_bitrate);I.uint32_audio_codec_bitrate=Math.round(Me*8/s),I.uint32_audio_total_bitrate=Math.round(Me*8/s)}else p.msg_audio_status={};if(p.msg_video_status&&_.msg_video_status){let I=_.msg_video_status;p.msg_video_status=p.msg_video_status.filter(R=>I.find($=>$.uint32_video_stream_type===R.uint32_video_stream_type)),p.msg_video_status.forEach(R=>{let $=I.find(Hm=>Hm.uint32_video_stream_type===R.uint32_video_stream_type),Me=$.uint32_video_receive,Go=$.uint32_video_origin_lost,Um=$.uint32_video_codec_bitrate,J=$.uint32_video_receive_fps,Vm=$.uint32_video_dec_fps;R.uint32_video_origin_lost=this.getDifferenceValue(Go,R.uint32_video_origin_lost),R.uint32_video_receive=this.getDifferenceValue(Me,R.uint32_video_receive)+R.uint32_video_origin_lost;let Bm=this.getDifferenceValue(Um,R.uint32_video_codec_bitrate);R.uint32_video_codec_bitrate=Math.round(Bm*8/s);let Fm=this.getDifferenceValue(J,R.uint32_video_receive_fps);R.uint32_video_receive_fps=Math.round(Fm/s),R.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Vm,R.uint32_video_dec_fps)/s);let $m=this.getDifferenceValue($.uint32_video_cache_ms_count,R.uint32_video_cache_ms_count);delete R.uint32_video_cache_ms_count,R.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue($.uint32_video_cache_ms,R.uint32_video_cache_ms)/$m)||0})}}),n&&i.receiverStats.forEach(p=>{if(p.audio.concealedSamples&&p.audio.totalSamplesReceived){let _=n.receiverStats.find(I=>I.userId===p.userId);if(_&&_.audio.concealedSamples&&_.audio.totalSamplesReceived){let I=p.audio.concealedSamples-_.audio.concealedSamples,A=p.audio.totalSamplesReceived-_.audio.totalSamplesReceived,R=Math.floor(I/A*1e3*s);if(R>s/5){let $=l.find(Me=>Me.msg_user_info.str_identifier===p.userId);$&&($.msg_audio_status.uint32_audio_block_time=R)}}}}),e}getStatsReport(s){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o.msg_up_stream_info.msg_network_status.uint32_ntp=_i($e()),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var dm=Ce(Pe());function am(r){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===r){let s=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,d=Math.round(t.domainLookupEnd-t.domainLookupStart),c=Math.round(t.requestStart-t.secureConnectionStart),l=Math.round(t.secureConnectionStart-t.connectStart),m=Math.round(t.responseStart-t.requestStart),p=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=w(D({},i),{totalCost:s,local:o,redirect:n,httpCache:a,dns:d,tcp:l,tls:c,request:m,response:p});break}}catch(e){}return i}function cm(r){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),s=`https://${r}/?t=${t}`;try{yield fetch(s)}catch(n){}clearTimeout(e);let o=am(s);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var W_=700,Lo=class extends dm.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"uplinkRTT",0);u(this,"uplinkLoss",0);u(this,"downlinkRTT",0);u(this,"downlinkLoss",0);u(this,"pingResults",{});u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=y.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(B.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(pe.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var d,c;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 s=(c=(d=this._room)==null?void 0:d.uplinkConnection)==null?void 0:c.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var d;return((d=a.getPeerConnection())==null?void 0:d.connectionState)===ne.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let d=t[a].getPeerConnection();if(!d)return;let{rtt:c,totalPacketsLost:l,totalPacketsReceived:m}=yield this.getStat(d);if(!this._downlinkPrevStatMap.has(d)){this._downlinkPrevStatMap.set(d,{totalPacketsLost:l,totalPacketsReceived:m});continue}let p=0,_=this._downlinkPrevStatMap.get(d),I=l-_.totalPacketsLost,A=m-_.totalPacketsReceived;I<=0||A<0?p=0:p=Math.round(I/(I+A)*100),this._downlinkPrevStatMap.set(d,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(d,{rtt:c,loss:p,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!ur())return t;let s=e.getReceivers();try{for(let o=0;o<s.length;o++)(yield s[o].getStats()).forEach(d=>{d.type==="candidate-pair"&&te(d.currentRoundTripTime)&&(t.rtt=Math.round(d.currentRoundTripTime*1e3)),d.type==="inbound-rtp"&&(d.mediaType===h.AUDIO||d.mediaType===h.VIDEO)&&(t.totalPacketsLost+=d.packetsLost,t.totalPacketsReceived+=d.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===ne.DISCONNECTED||e.connectionState===ne.FAILED||e.connectionState===ne.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=Q.run(Pi,()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(g.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,s={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(s=w(D({},s),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Lo.EVENT_NETWORK_QUALITY,s);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Lo.lastPingTime>t.interval*1e3){Lo.lastPingTime=Date.now();let a=t.domain.map(d=>cm(d).then(c=>({domain:d,cost:c.totalCost})));Promise.all(a).then(d=>{this.pingResults.isPoorNetwork=d.some(c=>c.cost>W_),this.pingResults.timestamp=o,this.pingResults.data=d,d.forEach(c=>{kvStatManager.addSuccessEvent({key:KV_REPORT_KEY_NETWORK.PING,cost:c.cost})}),this._log.warn(`All ping results: ${JSON.stringify(d)}`)}).catch(d=>{this._log.warn(`Error during pinging domains: ${d}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(Q.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:o,audioDelay:n})=>{let a=t.get(s);if(a){let d=this._room.remotePublishedUserMap.get(a);d==null||d.setDelay({videoDelay:o,audioDelay:n})}})}},Ki=Lo;u(Ki,"EVENT_NETWORK_QUALITY","0"),u(Ki,"lastPingTime",0);function J_({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return ar(t)?t.catch(s=>y.error(`${r.name}() error observed ${s}`)):t}catch(t){y.error(`${r.name}() error observed ${t}`)}}}var Oa=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._captureCostSum=0;this._captureCostCount=0;this.isDestroyed=!1;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=y.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ie(this[e])&&(this[e]=J_({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:Te,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,qs().then(i=>{this._basicInfo.string_os_version=hi(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),T.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(g.JOIN_START,this.handleJoinStart).addEvent(g.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(g.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(g.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(g.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(g.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(g.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(g.JOIN_FAILED,this.handleJoinFailed).addEvent(g.LEAVE_START,this.handleLeaveStart).addEvent(g.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(g.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(g.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(g.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(g.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(g.PUBLISH_START,this.handlePublishStart).addEvent(g.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(g.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(g.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(g.PLAY_TRACK_START,this.handlePlayStart).addEvent(g.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(g.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!vt(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(g.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(g.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(g.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(g.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(g.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>T.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Q.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(E(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),E(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),E(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:s,dns:o,tcp:n,tls:a,request:d,response:c}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=c}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof b?Number(e.getExtraCode()||e.getCode()):S.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:w(D({},j_),{msg_user_info:new wo({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,d=new wo({userId:o,tinyId:n,role:a==="anchor"?20:21}),c=Date.now(),l=`${o}_${t}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=c),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:c}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:c})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:c})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(s);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!vt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!vt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),o)){let{statsToReport:a,playStreamTime:d,subscribedTime:c}=o;a.uint32_video_render_first===0&&d-c<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let n=this._pathAuxiliaryMap.get(e);if(n&&o){let{statsToReport:a,playStreamTime:d,subscribedTime:c}=o;a.uint32_video_render_first===0&&d-c<=100&&(a.uint32_video_render_first=t-n.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,c,l,m;o&&(c=o,l=1),n&&(d=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:d,totalVideoDelay:c,audioDelayCount:m,videoDelayCount:l})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:s}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:d}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=d,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/at*100)>0&&(this._localStreamStat.totalAudioLevel+=o/at,this._localStreamStat.audioLevelCount++)}s.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:d}=o,c=n.str_identifier,l=this._room.remotePublishedUserMap.get(c);if(d.forEach(m=>{let p=m.uint32_video_stream_type===2,_=m.uint32_video_stream_type===7,I=`${c}_${p?"main":"auxiliary"}`,A=this._remoteStreamStatMap.get(I);if(!!A&&(p&&(l==null?void 0:l.remoteVideoTrack.isSubscribed)||_&&(l==null?void 0:l.remoteAuxiliaryTrack))){A.totalVideoFPS+=m.uint32_video_receive_fps,A.totalVideoBitrate+=m.uint32_video_codec_bitrate,A.videoCount++,A.statsToReport.uint32_video_width===0&&(A.statsToReport.uint32_video_width=m.uint32_video_width),A.statsToReport.uint32_video_height===0&&(A.statsToReport.uint32_video_height=m.uint32_video_height);let R=p?l.remoteVideoTrack:l.remoteAuxiliaryTrack;R.stat.jitterBufferDelay&&(A.videoJitterBufferDelay=R.stat.jitterBufferDelay),R.stat.framesReceived&&(A.statsToReport.uint32_video_consume_render_rate=Math.floor(R.stat.framesDecoded/R.stat.framesReceived*Cs(10,6)))}}),a){let m=`${c}_${"main"}`,p=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&p&&(l==null?void 0:l.remoteAudioTrack.isSubscribed)&&(p.totalAudioBitrate+=a.uint32_audio_codec_bitrate,p.audioCount++,l.remoteAudioTrack.stat.jitterBufferDelay&&(p.audioJitterBufferDelay=l.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/at*100)>0&&(p.totalAudioLevel+=a.uint32_audio_level/at,p.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof b?e.getExtraCode()||e.getCode():S.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Oi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Mi)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&er)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:l,count:m,audioDelayCount:p,videoDelayCount:_,totalAudioDelay:I,totalVideoDelay:A}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/m),p&&I&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(I/p),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&A&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(A/_))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Cr);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:d}=n.getDataFreezeDuration(e),{renderFreeze:c}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=d,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(c,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Cr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Cr)}),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>Cr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Cr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Cr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Cr)}getReportData(){this._basicInfo.uint32_networkType=zr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new wo({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Zs(this._signalInfo.relayIp),uint32_client_ip:Zs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Cs(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:Zs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return bn(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield tc(i),s=t instanceof ArrayBuffer,o=`${Fi(e,Di.KEY_POINT)}&gzip=${+s}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(v),this.uploadKVStat(dr)];n||a.push(ai({url:o,body:t})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=w(D({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield tc(e),s=`${Fi(+this._room.sdkAppId,Di.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(s,t)),o||ai({url:s,body:t})})}};N([qe({settings:{timeout:500,retries:3}})],Oa.prototype,"upload",1);var Cr=5e3,j_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},wo=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},um=Oa;var yu=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=P())}stop(){this._endTime===0&&(this._endTime=P())}getDuration(){return this._endTime===0?P()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Ss=yu;var bu=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(g.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(g.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(g.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,h.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!o||(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let n=new Ss,a=this._durationMap.get(o);a?this.isRecording(a.audio)||a.audio.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[n],video:[]})}else this.stopDurationItem(o,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let n=new Ss,a=this._durationMap.get(o);a?this.isRecording(a.video)||a.video.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[],video:[n]})}else this.stopDurationItem(o,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,o=new Ss,n=this._durationMap.get(s);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(o=>o.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,o)=>s+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},lm=bu;var Nu=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(g.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(g.PLAY_TRACK_START,this.onPlayTrackStart).set(g.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDataFreeze({key:o,userId:s,type:e})}).set(g.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}}).set(g.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!vt(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(g.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,o=this._dataFreezeMap.get(s),n=new Ss;o?o.durationItemList.push(n):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:o,muteState:n}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let o=s.durationItemList[s.durationItemList.length-1];o.stop();let n=o.getDuration();n>en?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return f(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=P();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=P();let d=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,d)}}})}onPlayTrackStart({track:i}){if(!vt(i)||!this.hitTest(i.room)||i.kind!==h.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<en&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=P(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},hm=Nu;var mm=Ce(Pe(),1);var q_=[1,0,0,0,1,1,0,1],Ma=class extends ot{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof Oe)try{this.setTexBuffer(q_)}catch(t){i.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,s,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,s,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var vu=class{constructor(i,e){this.node=i;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},ka=class extends ot{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});u(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let s=new vu(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(s.width,s.height),this.context instanceof Oe&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((s,o)=>(!o||!o.node.requestFrame(e))&&s,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:o,height:n,name:a}=this,d=Date.now(),c=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:c,name:a},D({parent:this.inputs.filter(l=>l).map(l=>l.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,s;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof Oe))try{(s=this.context.ctx)==null||s.deleteBuffer(e.positionBuffer)}catch(o){}})}};var X_=`#version 300 es
|
|
61
|
+
b=${r}:${t}\r
|
|
62
|
+
`),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(sm);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:W.PUBLISH,responseCommand:B.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof rt||this.localAuxVideoTrack instanceof rt,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:o,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,o)})}setSDPDirection(e,t,r="all"){let o=ue(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),mt(o)}acceptAnswer(e){return f(this,null,function*(){var t,r,o,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),p=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let _=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:_})}p&&(c=yield this.setBandwidth({bandwidth:p,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:m}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||m.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:c})}let l={type:e.type,sdp:c};yield this.setAnswer(l),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(W.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(Se(yu.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,responseCommand:B.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Ft(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ue(e).media.forEach((r,o)=>{if(r.type===h.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Or&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Zi?(this._log.error(Ne.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:U({key:w.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:U({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.PUBLISH_RESULT,code:e,message:t}})})}},Ts=yu;N([j(s=>function(...i){return new Promise((e,t)=>{let r=o=>{this._emitter.off("closed",r),t(new b({code:S.API_CALL_ABORTED,message:U({key:w.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",r),s.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",r)})})})],Ts.prototype,"publish",1),N([Xe(521715,!1)],Ts.prototype,"unpublish",1),N([Dt(He.prototype.afterConnect),zn(He.prototype.beforeConnect)],Ts.prototype,"connect",1);var Po=Ts;var Lo=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime",0);u(this,"_prevReport",{});u(this,"_prevStats",null);u(this,"_prevEncoderImplementation","");u(this,"_prevAuxEncoderImpl","");u(this,"_prevQualityLimitationReason","");u(this,"_prevAuxQualityLimitationReason","");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var l,m,p;let c,d;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===h.VIDEO){if(a.ssrc===r.video?(c=h.VIDEO,d=i.localMainVideoTrack):a.ssrc===r.small?c=h.SMALL:a.ssrc===r.auxiliary&&(d=i.localAuxVideoTrack,c=h.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,g(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),g(a.nackCount)||(e[c].nackCount=a.nackCount),g(a.pliCount)||(e[c].pliCount=a.pliCount),g(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),g(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),g(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!g(a.encoderImplementation)&&(c===h.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===h.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let I=2,A=this._prevEncoderImplementation;c===h.AUXILIARY&&(I=7,A=this._prevAuxEncoderImpl),T.emit("262",{userId:i.userId,streamType:I,prevImplementation:A,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===h.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===h.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!g(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(l=i.localMainVideoTrack)==null?void 0:l.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!g(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(m=i.localAuxVideoTrack)==null?void 0:m.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?Hi(a)&&(this.totalBytesSent=a.bytesSent,ee(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===h.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===h.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!g(a.audioLevel)&&((p=i.localMainAudioTrack)==null?void 0:p.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!g(a.frameWidth)){let _=h.SMALL;a.trackIdentifier===i.getVideoTrackId(h.VIDEO)||a.ssrc===r.video?_=h.VIDEO:(a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||a.ssrc===r.auxiliary)&&(_=h.AUXILIARY),e[_].frameWidth=a.frameWidth,e[_].frameHeight=a.frameHeight,e[_].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===h.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===h.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===h.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:o}=i,{muteState:n,subscribeState:a}=i;(this._spcStats||(yield t.getStats())).forEach(d=>{if(d.type==="inbound-rtp"){let l=(d.mediaType||d.kind)===h.AUDIO;if(l){if(d.ssrc!==o.audio||!n.hasAudio)return;e.audio.packetsReceived=d.packetsReceived,e.audio.bytesReceived=d.bytesReceived,e.audio.packetsLost=d.packetsLost,d.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=d.insertedSamplesForDeceleration),d.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=d.removedSamplesForAcceleration),d.totalSamplesDuration&&(e.audio.totalSamplesDuration=d.totalSamplesDuration),d.totalSamplesReceived&&(e.audio.totalSamplesReceived=d.totalSamplesReceived),d.concealedSamples&&(e.audio.concealedSamples=d.concealedSamples);let{remoteAudioTrack:m}=i;m.stat.packetsReceived=d.packetsReceived,m.stat.bytesReceived=d.bytesReceived,m.stat.packetsLost=d.packetsLost,e.audio.p2pDelay=m.stat.end2EndDelay,e.hasAudio=!0}else{if(se&&d.bytesReceived===0)return;let m;d.ssrc===o.video&&n.hasVideo&&(e.video.packetsReceived=d.packetsReceived,e.video.bytesReceived=d.bytesReceived,e.video.packetsLost=d.packetsLost,e.video.framesReceived=d.framesReceived,e.video.framesDecoded=d.framesDecoded,e.video.fpsDecoded=d.framesPerSecond,e.hasVideo=!0,m=i.remoteVideoTrack,n.hasSmall&&a.smallVideo&&(e.isSmallSubscribed=!0),d.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==d.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${d.decoderImplementation} HWDecoder: ${d.powerEfficientDecoder}`),T.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:d.decoderImplementation,codec:i.videoCodec,isHWCodec:d.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,d.decoderImplementation))),d.ssrc===o.auxiliary&&n.hasAuxiliary&&(e.auxiliary.packetsReceived=d.packetsReceived,e.auxiliary.bytesReceived=d.bytesReceived,e.auxiliary.packetsLost=d.packetsLost,e.auxiliary.framesReceived=d.framesReceived,e.auxiliary.framesDecoded=d.framesDecoded,e.auxiliary.fpsDecoded=d.framesPerSecond,m=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),m&&(m.stat.packetsReceived=d.packetsReceived,m.stat.bytesReceived=d.bytesReceived,m.stat.packetsLost=d.packetsLost,m.stat.framesReceived=d.framesReceived,m.stat.framesDecoded=d.framesDecoded,d.jitterBufferDelay&&(m.stat.jitterBufferDelay=Math.floor(d.jitterBufferDelay/d.jitterBufferEmittedCount*1e3)))}d.jitterBufferDelay&&(l?(e.audio.totalJitter=d.jitterBufferDelay,e.audio.totalJitterCount=d.jitterBufferEmittedCount):d.ssrc===o.video&&n.hasVideo?(e.video.totalJitter=d.jitterBufferDelay,e.video.totalJitterCount=d.jitterBufferEmittedCount):d.ssrc===o.auxiliary&&n.hasAuxiliary&&(e.auxiliary.totalJitter=d.jitterBufferDelay,e.auxiliary.totalJitterCount=d.jitterBufferEmittedCount))}else d.type==="candidate-pair"&&Hi(d)&&(this.totalBytesReceived=d.bytesReceived,ee(d.currentRoundTripTime)&&(e.rtt=Math.floor(d.currentRoundTripTime*1e3)));g(d.frameWidth)||((d.trackIdentifier===i.getMainStreamVideoTrackId()||d.ssrc===o.video)&&(e.video.frameWidth=d.frameWidth,e.video.frameHeight=d.frameHeight,i.remoteVideoTrack.stat.frameWidth=d.frameWidth,i.remoteVideoTrack.stat.frameHeight=d.frameHeight),(d.trackIdentifier===i.getAuxStreamVideoTrackId()||d.ssrc===o.auxiliary)&&(e.auxiliary.frameWidth=d.frameWidth,e.auxiliary.frameHeight=d.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=d.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=d.frameHeight)),!g(d.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&d.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=d.audioLevel||0,e.audio.totalAudioEnergy=d.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(o){this._log.warn(`failed to getStats on receiver connection ${o}`)}return e.rtt===0&&(e.rtt=((r=this.room.networkQuality)==null?void 0:r.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=P(),a=yield o.getStats(),c=P();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let d=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(m=>l.has(m.type)&&d.push(m)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(Qt(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m;if(!Qt(i.senderStats)){let p={uint32_audio_level:i.senderStats.audio.audioLevel*at,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(p.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*at),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let _=[];if(i.senderStats.video.bytesSent){let A={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};_.push(A)}if(i.senderStats.small.bytesSent){let A={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};_.push(A)}if(i.senderStats.auxiliary.bytesSent){let A={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};_.push(A)}let I={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:p,msg_video_status:_,msg_network_status:I}}let{statInterval:r}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(p=>{let _={msg_user_info:{str_identifier:p.userId,uint64_tinyid:p.tinyId},msg_network_status:{uint32_rtt:p.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(p.hasAudio){let I={uint32_audio_p2p_delay:p.audio.p2pDelay,uint32_audio_cache_ms:p.audio.totalJitter,uint32_audio_cache_ms_count:p.audio.totalJitterCount,uint32_audio_codec_bitrate:p.audio.bytesReceived,uint32_audio_total_bitrate:p.audio.bytesReceived,uint32_audio_level:p.audio.audioLevel*1e8,uint32_audio_energy:p.audio.totalAudioEnergy*1e6,uint32_audio_receive:p.audio.packetsReceived,uint32_audio_origin_lost:p.audio.packetsLost};_.msg_audio_status=I}if(p.hasVideo){let I=t.get(`${p.userId}_${qa}`),A=I?I.duration:0,C={uint32_video_stream_type:p.isSmallSubscribed?3:2,uint32_video_receive_fps:p.video.framesReceived,uint32_video_width:p.video.frameWidth,uint32_video_height:p.video.frameHeight,uint32_video_codec_bitrate:p.video.bytesReceived,uint32_video_receive:p.video.packetsReceived,uint32_video_origin_lost:p.video.packetsLost,uint32_video_block_time:A,uint32_video_dec_fps:p.video.framesDecoded,uint32_video_cache_ms:p.video.totalJitter,uint32_video_cache_ms_count:p.video.totalJitterCount};_.msg_video_status.push(C)}if(p.hasAuxiliary){let I=t.get(`${p.userId}_${Xa}`),A=I?I.duration:0,C={uint32_video_stream_type:7,uint32_video_receive_fps:p.auxiliary.framesReceived,uint32_video_width:p.auxiliary.frameWidth,uint32_video_height:p.auxiliary.frameHeight,uint32_video_codec_bitrate:p.auxiliary.bytesReceived,uint32_video_receive:p.auxiliary.packetsReceived+p.auxiliary.packetsLost,uint32_video_origin_lost:p.auxiliary.packetsLost,uint32_video_block_time:A,uint32_video_dec_fps:p.auxiliary.framesDecoded,uint32_video_cache_ms:p.auxiliary.totalJitter,uint32_video_cache_ms_count:p.auxiliary.totalJitterCount};_.msg_video_status.push(C)}e.msg_down_stream_info.push(_)});let o=this._prevReport,n=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let p=o.msg_up_stream_info.msg_audio_status,_=e.msg_up_stream_info.msg_audio_status;if(p.uint32_audio_codec_bitrate===0)_.uint32_audio_codec_bitrate=0;else{let I=this.getDifferenceValue(p.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(I*8/r),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_audio_codec_bitrate}(m=o.msg_device_info)!=null&&m.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/r):delete e.msg_device_info.uint32_audio_capture_cost}let a=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(p=>{let _=a.find(Pe=>Pe.uint32_video_stream_type===p.uint32_video_stream_type);if(!_||_.uint32_video_codec_bitrate===0){p.uint32_video_codec_bitrate=0,p.uint32_video_enc_fps=0,p.uint32_video_codec_fps=0;return}let I=0,A=0,C=0;_&&p.uint32_video_codec_bitrate>=_.uint32_video_codec_bitrate&&(I=_.uint32_video_codec_bitrate,A=_.uint32_video_enc_fps,C=_.uint32_video_codec_fps);let F=this.getDifferenceValue(I,p.uint32_video_codec_bitrate);p.uint32_video_codec_bitrate=Math.round(F*8/r),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=p.uint32_video_codec_bitrate,p.uint32_video_enc_fps=Math.round(this.getDifferenceValue(A,p.uint32_video_enc_fps)/r),p.uint32_video_codec_fps=Math.round(this.getDifferenceValue(C,p.uint32_video_codec_fps)/r),ni&&ai()===115&&_.uint32_video_width===0&&_.uint32_video_height===0&&_.uint32_video_codec_fps===0&&(p.uint32_video_codec_fps=p.uint32_video_enc_fps),g(_.uint32_key_frame_count)||(p.uint32_key_frame_count=Math.round(this.getDifferenceValue(_.uint32_key_frame_count,p.uint32_key_frame_count))),g(_.uint32_nack_count)||(p.uint32_nack_count=Math.round(this.getDifferenceValue(_.uint32_nack_count,p.uint32_nack_count))),g(_.uint32_pli_count)||(p.uint32_pli_count=Math.round(this.getDifferenceValue(_.uint32_pli_count,p.uint32_pli_count))),g(_.uint32_video_arq_packets)||(p.uint32_video_arq_packets=Math.round(this.getDifferenceValue(_.uint32_video_arq_packets,p.uint32_video_arq_packets))),g(_.uint32_encode_cost)||(p.uint32_encode_cost=Math.round(this.getDifferenceValue(_.uint32_encode_cost,p.uint32_encode_cost)/r)),g(_.uint32_send_packet_cost)||(p.uint32_send_packet_cost=Math.round(this.getDifferenceValue(_.uint32_send_packet_cost,p.uint32_send_packet_cost)/r))});let d=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(p=>d.find(_=>_.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid));let l=e.msg_down_stream_info;return l.forEach(p=>{let _=d.find(I=>I.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid);if(!Qt(p.msg_audio_status)&&!Qt(_.msg_audio_status)){let I=p.msg_audio_status,A=_.msg_audio_status,C=this.getDifferenceValue(A.uint32_audio_cache_ms_count,I.uint32_audio_cache_ms_count);delete I.uint32_audio_cache_ms_count,I.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(A.uint32_audio_cache_ms,I.uint32_audio_cache_ms)/C)||0;let F=this.room.remotePublishedUserMap.get(p.msg_user_info.str_identifier);F&&(F.remoteAudioTrack.stat.jitterBufferDelay=I.uint32_audio_cache_ms),I.uint32_audio_origin_lost=this.getDifferenceValue(A.uint32_audio_origin_lost,I.uint32_audio_origin_lost),I.uint32_audio_receive=this.getDifferenceValue(A.uint32_audio_receive,I.uint32_audio_receive),I.uint32_audio_receive+=I.uint32_audio_origin_lost;let Pe=this.getDifferenceValue(A.uint32_audio_codec_bitrate,I.uint32_audio_codec_bitrate);I.uint32_audio_codec_bitrate=Math.round(Pe*8/r),I.uint32_audio_total_bitrate=Math.round(Pe*8/r)}else p.msg_audio_status={};if(p.msg_video_status&&_.msg_video_status){let I=_.msg_video_status;p.msg_video_status=p.msg_video_status.filter(C=>I.find(F=>F.uint32_video_stream_type===C.uint32_video_stream_type)),p.msg_video_status.forEach(C=>{let F=I.find($m=>$m.uint32_video_stream_type===C.uint32_video_stream_type),Pe=F.uint32_video_receive,Wo=F.uint32_video_origin_lost,xm=F.uint32_video_codec_bitrate,J=F.uint32_video_receive_fps,wm=F.uint32_video_dec_fps;C.uint32_video_origin_lost=this.getDifferenceValue(Wo,C.uint32_video_origin_lost),C.uint32_video_receive=this.getDifferenceValue(Pe,C.uint32_video_receive)+C.uint32_video_origin_lost;let Um=this.getDifferenceValue(xm,C.uint32_video_codec_bitrate);C.uint32_video_codec_bitrate=Math.round(Um*8/r);let Vm=this.getDifferenceValue(J,C.uint32_video_receive_fps);C.uint32_video_receive_fps=Math.round(Vm/r),C.uint32_video_dec_fps=Math.round(this.getDifferenceValue(wm,C.uint32_video_dec_fps)/r);let Bm=this.getDifferenceValue(F.uint32_video_cache_ms_count,C.uint32_video_cache_ms_count);delete C.uint32_video_cache_ms_count,C.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(F.uint32_video_cache_ms,C.uint32_video_cache_ms)/Bm)||0})}}),n&&i.receiverStats.forEach(p=>{if(p.audio.concealedSamples&&p.audio.totalSamplesReceived){let _=n.receiverStats.find(I=>I.userId===p.userId);if(_&&_.audio.concealedSamples&&_.audio.totalSamplesReceived){let I=p.audio.concealedSamples-_.audio.concealedSamples,A=p.audio.totalSamplesReceived-_.audio.totalSamplesReceived,C=Math.floor(I/A*1e3*r);if(C>r/5){let F=l.find(Pe=>Pe.msg_user_info.str_identifier===p.userId);F&&(F.msg_audio_status.uint32_audio_block_time=C)}}}}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o.msg_up_stream_info.msg_network_status.uint32_ntp=ro(ot()),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var am=ye(xe());function om(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),d=Math.round(t.requestStart-t.secureConnectionStart),l=Math.round(t.secureConnectionStart-t.connectStart),m=Math.round(t.responseStart-t.requestStart),p=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=x(D({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:c,tcp:l,tls:d,request:m,response:p});break}}catch(e){}return i}function nm(s){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=om(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var G_=700,xo=class extends am.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"uplinkRTT",0);u(this,"uplinkLoss",0);u(this,"downlinkRTT",0);u(this,"downlinkLoss",0);u(this,"pingResults",{});u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=y.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(B.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(pe.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===ne.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:l,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m});continue}let p=0,_=this._downlinkPrevStatMap.get(c),I=l-_.totalPacketsLost,A=m-_.totalPacketsReceived;I<=0||A<0?p=0:p=Math.round(I/(I+A)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:p,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!cr())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&ee(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===h.AUDIO||c.mediaType===h.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(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===ne.DISCONNECTED||e.connectionState===ne.FAILED||e.connectionState===ne.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=Z.run(Mi,()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=x(D({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(xo.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-xo.lastPingTime>t.interval*1e3){xo.lastPingTime=Date.now();let a=t.domain.map(c=>nm(c).then(d=>({domain:c,cost:d.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(d=>d.cost>G_),this.pingResults.timestamp=o,this.pingResults.data=c,c.forEach(d=>{kvStatManager.addSuccessEvent({key:KV_REPORT_KEY_NETWORK.PING,cost:d.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&&(Z.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}},zi=xo;u(zi,"EVENT_NETWORK_QUALITY","0"),u(zi,"lastPingTime",0);function W_({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return or(t)?t.catch(r=>y.error(`${s.name}() error observed ${r}`)):t}catch(t){y.error(`${s.name}() error observed ${t}`)}}}var Da=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._captureCostSum=0;this._captureCostCount=0;this.isDestroyed=!1;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=y.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ie(this[e])&&(this[e]=W_({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:Ie,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Xs().then(i=>{this._basicInfo.string_os_version=li(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),T.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!Nt(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>T.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Z.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(g(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),g(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),g(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:o,tcp:n,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof b?Number(e.getExtraCode()||e.getCode()):S.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:x(D({},J_),{msg_user_info:new wo({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new wo({userId:o,tinyId:n,role:a==="anchor"?20:21}),d=Date.now(),l=`${o}_${t}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=d),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!Nt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!Nt(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(r&&(r.statsToReport.uint64_render_first_frame_time===0&&(r.statsToReport.uint64_render_first_frame_time=t),o)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-r.sendSubscribeCMDTime)}let n=this._pathAuxiliaryMap.get(e);if(n&&o){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-n.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,m;o&&(d=o,l=1),n&&(c=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:m,videoDelayCount:l})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/at*100)>0&&(this._localStreamStat.totalAudioLevel+=o/at,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,d=n.str_identifier,l=this._room.remotePublishedUserMap.get(d);if(c.forEach(m=>{let p=m.uint32_video_stream_type===2,_=m.uint32_video_stream_type===7,I=`${d}_${p?"main":"auxiliary"}`,A=this._remoteStreamStatMap.get(I);if(!!A&&(p&&(l==null?void 0:l.remoteVideoTrack.isSubscribed)||_&&(l==null?void 0:l.remoteAuxiliaryTrack))){A.totalVideoFPS+=m.uint32_video_receive_fps,A.totalVideoBitrate+=m.uint32_video_codec_bitrate,A.videoCount++,A.statsToReport.uint32_video_width===0&&(A.statsToReport.uint32_video_width=m.uint32_video_width),A.statsToReport.uint32_video_height===0&&(A.statsToReport.uint32_video_height=m.uint32_video_height);let C=p?l.remoteVideoTrack:l.remoteAuxiliaryTrack;C.stat.jitterBufferDelay&&(A.videoJitterBufferDelay=C.stat.jitterBufferDelay),C.stat.framesReceived&&(A.statsToReport.uint32_video_consume_render_rate=Math.floor(C.stat.framesDecoded/C.stat.framesReceived*Rs(10,6)))}}),a){let m=`${d}_${"main"}`,p=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&p&&(l==null?void 0:l.remoteAudioTrack.isSubscribed)&&(p.totalAudioBitrate+=a.uint32_audio_codec_bitrate,p.audioCount++,l.remoteAudioTrack.stat.jitterBufferDelay&&(p.audioJitterBufferDelay=l.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/at*100)>0&&(p.totalAudioLevel+=a.uint32_audio_level/at,p.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof b?e.getExtraCode()||e.getCode():S.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&vi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Di)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Ki)>=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:l,count:m,audioDelayCount:p,videoDelayCount:_,totalAudioDelay:I,totalVideoDelay:A}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(l/m),p&&I&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(I/p),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&A&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(A/_))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Rr);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:d}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(d,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Rr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Rr)}),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>Rr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Rr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Rr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Rr)}getReportData(){this._basicInfo.uint32_networkType=Qr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new wo({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:eo(this._signalInfo.relayIp),uint32_client_ip:eo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Rs(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:eo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return Nn(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield tc(i),r=t instanceof ArrayBuffer,o=`${Vi(e,Ni.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(v),this.uploadKVStat(ar)];n||a.push(oi({url:o,body:t})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=x(D({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield tc(e),r=`${Vi(+this._room.sdkAppId,Ni.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||oi({url:r,body:t})})}};N([je({settings:{timeout:500,retries:3}})],Da.prototype,"upload",1);var Rr=5e3,J_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},wo=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},cm=Da;var bu=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=P())}stop(){this._endTime===0&&(this._endTime=P())}getDuration(){return this._endTime===0?P()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Ss=bu;var Nu=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(E.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_${"main"}`,h.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);!o||(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let n=new Ss,a=this._durationMap.get(o);a?this.isRecording(a.audio)||a.audio.push(n):this._durationMap.set(o,{userId:r,type:e,audio:[n],video:[]})}else this.stopDurationItem(o,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let n=new Ss,a=this._durationMap.get(o);a?this.isRecording(a.video)||a.video.push(n):this._durationMap.set(o,{userId:r,type:e,audio:[],video:[n]})}else this.stopDurationItem(o,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new Ss,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(o=>o.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,o)=>r+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},dm=Nu;var vu=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!Nt(i)||!this.hitTest(i.room)||r!==h.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new Ss;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let r=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!r)return;let{userId:o,muteState:n}=r;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&r.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let n=o.getDuration();n>tn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return f(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=P();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=P();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!Nt(i)||!this.hitTest(i.room)||i.kind!==h.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<tn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=P(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},um=vu;var lm=ye(xe(),1);var j_=[1,0,0,0,1,1,0,1],Oa=class extends st{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof ke)try{this.setTexBuffer(j_)}catch(t){i.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,r,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,r,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Du=class{constructor(i,e){this.node=i;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Ma=class extends st{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});u(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new Du(e,t);this.inputs[t.zIndex]=r}resize(e,t){let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof ke&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((r,o)=>(!o||!o.node.requestFrame(e))&&r,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),d=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:d,name:a},D({parent:this.inputs.filter(l=>l).map(l=>l.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof ke))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var q_=`#version 300 es
|
|
63
63
|
in vec2 a_position;
|
|
64
64
|
in vec2 a_texCoord;
|
|
65
65
|
out vec2 v_texCoord;
|
|
66
66
|
void main() {
|
|
67
67
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
68
68
|
v_texCoord = a_texCoord;
|
|
69
|
-
}`,
|
|
69
|
+
}`,X_=`#version 300 es
|
|
70
70
|
precision highp float;
|
|
71
71
|
uniform sampler2D u_texture;
|
|
72
72
|
uniform sampler2D mask;
|
|
@@ -75,13 +75,13 @@ in vec2 v_texCoord;
|
|
|
75
75
|
out vec4 outColor;
|
|
76
76
|
void main() {
|
|
77
77
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
78
|
-
}`,Pa=class extends bi{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(s){e.log.error(s),e.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${s.message||s}`}))}}init(e){var o,n;let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:a,y:d,width:c,height:l}=e.waterMark;this.wasm.setWaterMark(a,d,c,l)}if(e.beautyParams){let{beauty:a,brightness:d,ruddy:c}=e.beautyParams;this.wasm.setBeauty(a,d,c,(o=this.context._canvas)==null?void 0:o.width,(n=this.context._canvas)==null?void 0:n.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(s.FRAGMENT_SHADER,Q_),d=this.context.createShader(s.VERTEX_SHADER,X_);this._prePrograme=this.context.createProgram(d,a),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var s;let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(s=this._selfieSegmentation)==null||s.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var d,c,l,m;let t=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback(s);let{videoWidth:o,videoHeight:n}=s;s.width=o,s.height=n;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():(d=this._selfieSegmentation)==null||d.bindTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}return this.width!==o||this.height!==n||!a?(this.resize(o,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,s)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,s),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(c=this._selfieSegmentation)==null||c.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(l=this._selfieSegmentation)==null||l.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,o,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,o,n,0)),(m=this._selfieSegmentation)==null||m.send(o,n),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var La=class extends mm.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"_virtualBackgroundAbortCallback");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",y.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new ze({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new 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 Oe({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update()})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=Q.run(rr,()=>{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(),Q.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Jr||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:s,error:t}):v.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new Oe({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let s=this.cameraTrack,{small:o,settings:n,player:a}=s;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new pa(this.smallVideoContext,o,this.log)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Jr&&a.setCanvas(e);let d=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),d=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${d?d.label:"no output track"}`),s.setOutputMediaStreamTrack(d)}catch(s){this.log.error("set main output failed",s)}}update(){return f(this,null,function*(){var s,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),di===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof bi?(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 bi?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(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new ma(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Pa(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Ma(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new ka(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,o,n;if(e instanceof st)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof me)return this.log.info("change video input",(s=e.mediaTrack)==null?void 0:s.label),this.setCameraTrack(e);if(e instanceof Mt){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}configPipeline(e){e instanceof Mt}removeInput(e){var t;e instanceof st?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof me?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Mt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return f(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let o=s.getContext("2d");if(!o)throw new b({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:d,width:c,height:l})=>{o.drawImage(n,a,d,c,l)}),to(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield to((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:o=0,width:n=t.width,height:a=t.height,type:d="watermark",zIndex:c=2}=e;this.pushWaterMarkImageList({x:s,y:o,width:n,height:a,image:t,zIndex:c,type:d,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var t,s,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return f(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield to(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new b({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};var z_=0;var wa=class extends H{constructor(e){super("room");this.seq=++z_;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}};this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this.enableChorus=!1;this._isUsingCachedSchedule=!1;this._log=y.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,le(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),le(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),le(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new um({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new lm({room:this}),this.badCaseDetector=new hm({room:this}),this.audioManager=new ea(this),this.videoManager=new La(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(K(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(et(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(yc([a,a]),Zi(`https://${a}`)):(o&&Zi(o),n&&yc(n))}T.once(g.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:$i.main,sched_back_domain:$i.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:S.INVALID_OPERATION,message:U({key:x.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ne.INVALID_DESTROY),new b({code:S.INVALID_OPERATION,message:U({key:x.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,T.emit(g.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var o,n;let s=P();try{let{isCached:a,result:d,detailCost:c}=yield fl({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Te,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${Nt(d,{keysToExclude:["username","credential"]})}`),a&&T.once(g.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=D(D({},this.scheduleResult),d),te((o=d.config)==null?void 0:o.retryCount)&&Qa(d.config.retryCount),K((n=d.config)==null?void 0:n.loggerDomain)&&Zi(d.config.loggerDomain),T.emit(g.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),v.addSuccessEvent({key:521700,cost:P()-s,split:50})}catch(a){throw v.addFailedEvent({key:521700,error:a}),a}})}};var fm=Ce(Pe(),1);var pm=Symbol("instance"),Pw=Symbol("abortCtrl"),Du=Symbol("cacheResult"),xo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Bo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Uo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Y_(r){return typeof r=="object"&&r&&"then"in r}var Vo=new Map;function Ou(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let d=Vo.get(t)||[];Vo.has(t)||Vo.set(t,d),d.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...d){let c=this;if(e.context&&(c=ce.get(typeof e.context=="function"?e.context.call(this,...d):e.context)),c.state===i)return c[Du];c.state instanceof xo&&c.state.action==e.abortAction&&c.state.abort(c);let l=null;if(Array.isArray(r)?r.length==0?c.state instanceof xo&&c.state.abort(c):(typeof c.state!="string"||!r.includes(c.state))&&(l=new Uo(c._state,`${c.name} ${n} to ${i} failed: current state ${c._state} not in from config`)):r!==c.state&&(l=new Uo(c._state,`${c.name} ${n} to ${i} failed: current state ${c._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=c.state,p=new xo(m,i,n);Bo.call(c,p);let _=A=>{var R;return c[Du]=A,p.aborted||(Bo.call(c,i),(R=e.success)===null||R===void 0||R.call(this,c[Du])),A},I=A=>{let R=A instanceof Error?A.message:String(A);if(Bo.call(c,m,A),e.fail)e.fail.call(this,new Uo(c._state,`action '${n}' failed :${R}`,A instanceof Error?A:new Error(R)));else{if(e.ignoreError)return A;throw A}};try{let A=a.apply(this,d);return Y_(A)?A.then(_).catch(I):_(A)}catch(A){I(A)}}}}var K_=(()=>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 Bo(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(ce.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var ce=class extends fm.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ce.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[pm];s?this.name=s.name+"-"+s.count++:t[pm]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Vo.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Vo.has(a)&&(a.stateDiagram.forEach(c=>t.add(c)),a.allStates.forEach(c=>n.add(c))),e.forEach(({from:c,to:l,action:m})=>{typeof c=="string"?s.push({from:c,to:l,action:m}):c.length?c.forEach(p=>{s.push({from:p,to:l,action:m})}):o.push({to:l,action:m})}),s.forEach(({from:c,to:l,action:m})=>{n.add(c),n.add(l),n.add(m+"ing"),t.add(`${c} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${c} : ${m} \u{1F534}`)}),o.forEach(({to:c,action:l})=>{t.add(`${l}ing --> ${c} : ${l} \u{1F7E2}`),n.forEach(m=>{m!==c&&t.add(`${m} --> ${l}ing : ${l}`)})});let d=[...t];return Object.defineProperties(i,{stateDiagram:{value:d},allStates:{value:n}}),d}static get(i){let e;return typeof i=="string"?(e=ce.instances.get(i),e||ce.instances.set(i,e=new ce(i,void 0,Object.create(ce.prototype)))):(e=ce.instances2.get(i),e||ce.instances2.set(i,e=new ce(i.constructor.name,void 0,Object.create(ce.prototype)))),e}static getState(i){var e;return(e=ce.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){K_(ce.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Bo.call(this,i)}};ce.STATECHANGED="stateChanged";ce.UPDATEAFSM="updateAFSM";ce.INIT="[*]";ce.ON="on";ce.OFF="off";ce.instances=new Map;ce.instances2=new WeakMap;var Nm=Ce(Pe());var Mu=Ce(Su());var _m=r=>{let i=ue(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var o;if(t.ssrcs&&!E(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(d=>d.attribute==="cname")[1])==null?void 0:o.id);switch(s){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function gm(r){var e;let i=[];for(let t=0;t<r.rtp.length;t++){if(["rtx","red","ulpfec"].includes(r.rtp[t].codec))continue;let s=r.fmtp.filter(o=>o.payload===r.rtp[t].payload)[0];i.push({payload:r.rtp[t].payload,codec:r.rtp[t].codec,fmtp:s?s.config:"",rate:r.rtp[t].rate,rtx:((e=r.rtp[t+1])==null?void 0:e.codec)==="rtx"?r.rtp[t+1].payload:0,rtcpFb:((r==null?void 0:r.rtcpFb)||[]).filter(o=>o.payload===r.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function Z_(){return f(this,null,function*(){let r=new RTCPeerConnection;r.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield r.createOffer();if(!i.sdp)return[];let e=ue(i.sdp),t=gm(e.media[0]);return r.close(),t})}var Em=(r,i)=>f(void 0,null,function*(){var d;let e=ue(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],o=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(c=>({id:c.value,uri:c.uri}))),o.ext&&(t.video.extensions=o.ext.map(c=>({id:c.value,uri:c.uri})));let n={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(d=s.rtcpFb)==null||d.forEach(({payload:c,type:l,subtype:m})=>{if(c===n.payload){let p={id:l,params:[]};m&&p.params.push(m),n.rtcpFb.push(p)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...gm(o)].filter(c=>a.includes(c.codec.toLocaleLowerCase())),t.video.decoders=(yield Z_()).filter(c=>["h264","vp8"].includes(c.codec.toLocaleLowerCase())),t}),Tm=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ue(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(ku({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&o.media.push(s.media.find(a=>a.mid==="dc")),mt(o)},ku=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:s=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s)(i.video.decoders||i.video.codecs).forEach(n=>{yr(o,n)});else{let n=i.video.codecs.findIndex(d=>d.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];yr(o,a)}return o},yr=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`.trim(),r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function eg(r){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);r.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function tg(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function ig(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function rg(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Sm=(r,i,e)=>{let t=Mu.default.parse(r);return t.media.forEach((s,o)=>{var n;(s.type===h.AUDIO||s.type===h.VIDEO)&&(tg(s),ig(s),rg(s),eg(s),s.type===h.VIDEO&&(o<4?(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],i.video.codecs.forEach(a=>yr(s,a))):e&&(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],(e.video.decoders||e.video.codecs).forEach(a=>yr(s,a))))),((n=s.payloads)==null?void 0:n.includes("datachannel"))&&t.groups&&s.mid&&(t.groups[0].mids=t.groups[0].mids.replace(s.mid,"dc"),s.mid="dc")}),Mu.default.write(t)};var Im=Ce(Pe());var xa=class extends Im.EventEmitter{constructor(e){super();this.room=e;u(this,"mainFpsHealth",1);u(this,"mainBitrateHealth",1);u(this,"badMainBitrateHealthCount",0);u(this,"lastEmitBadHealthTime",0);u(this,"log");!fe&&Ct&&T.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:s,codec:o}){if(!(e||t===7||o!=="h264")){if(!s){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let s=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=s)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:s}=this.room;s&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/s.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){T.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};u(xa,"EVENT_BAD_HEALTH","bad_health");var Am=xa;function Rm({seiMessageList:r,isAudio:i,getNtpTime:e}){return new TransformStream({transform(t,s){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o,ntpTime:e()})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:r})}),s.enqueue(o)}})}function Cm({userId:r,streamType:i,isAudio:e}){return new TransformStream({transform(t,s){let o=t;e?audioDecodePipeline.forEach(n=>{o=n({frame:o,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:r,streamType:i})}})}):videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(d=>{self.postMessage({type:"sei",seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:r,streamType:i})})}})}),s.enqueue(o)}})}function ym(r){let i=[Ri],e=[cu,nu,au,ou,Rm,Cm,_i,io],t=()=>{let c=[],l=[],m=[],p=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(c.push(_.data.data),_.data.small&&m.push(_.data.data)):l.push(_.data.data);break;case"ntp-offset":p=_.data.data;break}},self.onrtctransform=_=>{let{options:I}=_.transformer,A=I.isReceiver?Cm({userId:I.userId,streamType:I.streamType,isAudio:I.isAudio}):Rm({getNtpTime:()=>Date.now()+p,isAudio:I.isAudio,seiMessageList:I.isMain?I.small?m:c:l});_.transformer.readable.pipeThrough(A).pipeTo(_.transformer.writable)}},s=`const videoEncodePipeline=[${r.videoEncodePipeline.toString()}];
|
|
79
|
-
const videoDecodePipeline=[${
|
|
80
|
-
const audioEncodePipeline = [${
|
|
81
|
-
const audioDecodePipeline = [${
|
|
78
|
+
}`,ka=class extends Ri{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(r){e.log.error(r),e.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))}}init(e){var o,n;let t=e.Wasm,r=this.context.ctx;if(this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:a,y:c,width:d,height:l}=e.waterMark;this.wasm.setWaterMark(a,c,d,l)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:d}=e.beautyParams;this.wasm.setBeauty(a,c,d,(o=this.context._canvas)==null?void 0:o.width,(n=this.context._canvas)==null?void 0:n.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(r.FRAGMENT_SHADER,X_),c=this.context.createShader(r.VERTEX_SHADER,q_);this._prePrograme=this.context.createProgram(c,a),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var r;let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(r=this._selfieSegmentation)==null||r.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var c,d,l,m;let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback(r);let{videoWidth:o,videoHeight:n}=r;r.width=o,r.height=n;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():(c=this._selfieSegmentation)==null||c.bindTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}return this.width!==o||this.height!==n||!a?(this.resize(o,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(d=this._selfieSegmentation)==null||d.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(l=this._selfieSegmentation)==null||l.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,o,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,o,n,0)),(m=this._selfieSegmentation)==null||m.send(o,n),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Pa=class extends lm.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"_virtualBackgroundAbortCallback");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",y.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Qe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Qe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update()})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=Z.run(tr,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Wr||this._isMixScreen||this._isMirror||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 ke({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:o,settings:n,player:a}=r;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new ma(this.smallVideoContext,o,this.log)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Wr&&a.setCanvas(e);let c=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${c?c.label:"no output track"}`),r.setOutputMediaStreamTrack(c)}catch(r){this.log.error("set main output failed",r)}}update(){return f(this,null,function*(){var r,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),ci===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ri?(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 Ri?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(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new ha(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new ka(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Oa(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Ma(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),(r=this.waterMarkNode)==null||r.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof rt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof me)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof Ot){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}configPipeline(e){e instanceof Ot}removeInput(e){var t;e instanceof rt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof me?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Ot&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let o=r.getContext("2d");if(!o)throw new b({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:d,height:l})=>{o.drawImage(n,a,c,d,l)}),io(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield io((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var t,r,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((r=this.cameraTrack)==null?void 0:r.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return f(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield io(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new b({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};var Q_=0;var La=class extends H{constructor(e){super("room");this.seq=++Q_;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.checkSystemResult={result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}};this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this.enableChorus=!1;this._isUsingCachedSchedule=!1;this._log=y.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,le(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),le(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),le(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new cm({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new dm({room:this}),this.badCaseDetector=new um({room:this}),this.audioManager=new ta(this),this.videoManager=new Pa(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Y(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Ze(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(bc([a,a]),Yi(`https://${a}`)):(o&&Yi(o),n&&bc(n))}T.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Bi.main,sched_back_domain:Bi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let o=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:S.INVALID_OPERATION,message:U({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ne.INVALID_DESTROY),new b({code:S.INVALID_OPERATION,message:U({key:w.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,T.emit(E.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var o,n;let r=P();try{let{isCached:a,result:c,detailCost:d}=yield _l({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ie,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${bt(c,{keysToExclude:["username","credential"]})}`),a&&T.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=D(D({},this.scheduleResult),c),ee((o=c.config)==null?void 0:o.retryCount)&&Qa(c.config.retryCount),Y((n=c.config)==null?void 0:n.loggerDomain)&&Yi(c.config.loggerDomain),T.emit(E.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),v.addSuccessEvent({key:521700,cost:P()-r,split:50})}catch(a){throw v.addFailedEvent({key:521700,error:a}),a}})}};var mm=ye(xe(),1);var hm=Symbol("instance"),kx=Symbol("abortCtrl"),Ou=Symbol("cacheResult"),Uo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,$o.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Vo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function z_(s){return typeof s=="object"&&s&&"then"in s}var Bo=new Map;function Mu(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let c=Bo.get(t)||[];Bo.has(t)||Bo.set(t,c),c.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=ce.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[Ou];d.state instanceof Uo&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(s)?s.length==0?d.state instanceof Uo&&d.state.abort(d):(typeof d.state!="string"||!s.includes(d.state))&&(l=new Vo(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not in from config`)):s!==d.state&&(l=new Vo(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${s}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,p=new Uo(m,i,n);$o.call(d,p);let _=A=>{var C;return d[Ou]=A,p.aborted||($o.call(d,i),(C=e.success)===null||C===void 0||C.call(this,d[Ou])),A},I=A=>{let C=A instanceof Error?A.message:String(A);if($o.call(d,m,A),e.fail)e.fail.call(this,new Vo(d._state,`action '${n}' failed :${C}`,A instanceof Error?A:new Error(C)));else{if(e.ignoreError)return A;throw A}};try{let A=a.apply(this,c);return z_(A)?A.then(_).catch(I):_(A)}catch(A){I(A)}}}}var Y_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function $o(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(ce.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var ce=class extends mm.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ce.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[hm];r?this.name=r.name+"-"+r.count++:t[hm]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Bo.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Bo.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?r.push({from:d,to:l,action:m}):d.length?d.forEach(p=>{r.push({from:p,to:l,action:m})}):o.push({to:l,action:m})}),r.forEach(({from:d,to:l,action:m})=>{n.add(d),n.add(l),n.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),o.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),n.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=ce.instances.get(i),e||ce.instances.set(i,e=new ce(i,void 0,Object.create(ce.prototype)))):(e=ce.instances2.get(i),e||ce.instances2.set(i,e=new ce(i.constructor.name,void 0,Object.create(ce.prototype)))),e}static getState(i){var e;return(e=ce.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Y_(ce.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){$o.call(this,i)}};ce.STATECHANGED="stateChanged";ce.UPDATEAFSM="updateAFSM";ce.INIT="[*]";ce.ON="on";ce.OFF="off";ce.instances=new Map;ce.instances2=new WeakMap;var ym=ye(xe());var ku=ye(Iu());var pm=s=>{let i=ue(s),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var o;if(t.ssrcs&&!g(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function fm(s){var e;let i=[];for(let t=0;t<s.rtp.length;t++){if(["rtx","red","ulpfec"].includes(s.rtp[t].codec))continue;let r=s.fmtp.filter(o=>o.payload===s.rtp[t].payload)[0];i.push({payload:s.rtp[t].payload,codec:s.rtp[t].codec,fmtp:r?r.config:"",rate:s.rtp[t].rate,rtx:((e=s.rtp[t+1])==null?void 0:e.codec)==="rtx"?s.rtp[t+1].payload:0,rtcpfb:((s==null?void 0:s.rtcpFb)||[]).filter(o=>o.payload===s.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function K_(){return f(this,null,function*(){let s=new RTCPeerConnection;s.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield s.createOffer();if(!i.sdp)return[];let e=ue(i.sdp),t=fm(e.media[0]);return s.close(),t})}var _m=(s,i)=>f(void 0,null,function*(){var c;let e=ue(s),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(d=>({id:d.value,uri:d.uri}))),o.ext&&(t.video.extensions=o.ext.map(d=>({id:d.value,uri:d.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(c=r.rtcpFb)==null||c.forEach(({payload:d,type:l,subtype:m})=>{if(d===n.payload){let p={id:l,params:[]};m&&p.params.push(m),n.rtcpfb.push(p)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...fm(o)].filter(d=>a.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield K_()).filter(d=>["h264","vp8"].includes(d.codec.toLocaleLowerCase())),t}),Em=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=ue(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:s.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:s.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:s.dtls.hash,hash:s.dtls.fingerprint},fmtp:[{payload:s.audio.codecs[0].payload,config:s.audio.codecs[0].fmtp}],icePwd:s.ice.password,iceUfrag:s.ice.ufrag,mid:"0",payloads:String(s.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:h.AUDIO,setup:s.dtls.setup,rtcpFb:s.audio.codecs[0].rtcpfb.map(a=>({payload:s.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:s.audio.codecs[0].payload,codec:s.audio.codecs[0].codec,rate:s.audio.codecs[0].rate,encoding:s.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Pu({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),mt(o)},Pu=({mid:s,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(s),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(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=>{yr(o,a)})}else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];yr(o,a)}return o},yr=(s,i)=>{s.payloads=`${s.payloads} ${i.payload}`.trim(),s.fmtp.push({payload:i.payload,config:i.fmtp}),s.rtcpFb=[...s.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],s.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(s.payloads=`${s.payloads} ${i.rtx}`,s.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),s.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function Z_(s){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);s.ext&&(s.ext=s.ext.filter(e=>!i.has(e.uri)))}function eE(s){if(!s.rtcpFb)return;let i=[];s.rtcpFb.forEach((e,t)=>{var r;i.push(e),s.rtcpFb&&((r=s.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),s.rtcpFb=i}function tE(s){s.type===h.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function iE(s){s.type===h.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var gm=(s,i,e)=>{let t=ku.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===h.AUDIO||r.type===h.VIDEO)&&(eE(r),tE(r),iE(r),Z_(r),r.type===h.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>yr(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=>yr(r,c))}}((n=r.payloads)==null?void 0:n.includes("datachannel"))&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),ku.default.write(t)};var Tm=ye(xe());var xa=class extends Tm.EventEmitter{constructor(e){super();this.room=e;u(this,"mainFpsHealth",1);u(this,"mainBitrateHealth",1);u(this,"badMainBitrateHealthCount",0);u(this,"lastEmitBadHealthTime",0);u(this,"log");!fe&&Ct&&T.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:o}){if(!(e||t===7||o!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){T.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};u(xa,"EVENT_BAD_HEALTH","bad_health");var Sm=xa;function Im({seiMessageList:s,isAudio:i,getNtpTime:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o,ntpTime:e()})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s})}),r.enqueue(o)}})}function Am({userId:s,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let o=t;e?audioDecodePipeline.forEach(n=>{o=n({frame:o,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:s,streamType:i})}})}):videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:s,streamType:i})})}})}),r.enqueue(o)}})}function Cm(s){let i=[Ii],e=[du,au,cu,nu,Im,Am,ro,Pc],t=()=>{let d=[],l=[],m=[],p=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(d.push(_.data.data),_.data.small&&m.push(_.data.data)):l.push(_.data.data);break;case"ntp-offset":p=_.data.data;break}},self.onrtctransform=_=>{let{options:I}=_.transformer,A=I.isReceiver?Am({userId:I.userId,streamType:I.streamType,isAudio:I.isAudio}):Im({getNtpTime:()=>Date.now()+p,isAudio:I.isAudio,seiMessageList:I.isMain?I.small?m:d:l});_.transformer.readable.pipeThrough(A).pipeTo(_.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
|
|
79
|
+
const videoDecodePipeline=[${s.videoDecodePipeline.toString()}];
|
|
80
|
+
const audioEncodePipeline = [${s.audioEncodePipeline.toString()}];
|
|
81
|
+
const audioDecodePipeline = [${s.audioDecodePipeline.toString()}];`,o=`(()=>{${i.map(d=>`const ${d.name}=(()=>${d.toString()})()`).join(`
|
|
82
82
|
`)}
|
|
83
|
-
${e.map(
|
|
84
|
-
`)};(${t})();${
|
|
85
|
-
offer: ${e==null?void 0:e.sdp}`),s}})}setPriority(e="high"){if(!!this._peerConnection)try{this._peerConnection.getSenders().forEach(s=>{let o=s.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,s.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var s,o;try{if(this.currentState==="CONNECTED")return;let n=P(),a={type:"answer",sdp:Tm({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(a),yield this.waitForPeerConnectionConnected();let d=((s=this._room.scheduleResult.config)==null?void 0:s.priority)||((o=this._room.joinParams)==null?void 0:o.priority)||new URLSearchParams(location.search).get("priority");d&&this.setPriority(d),t||v.addSuccessEvent({key:521703,cost:P()-n})}catch(n){let a=n instanceof b&&n.code===S.API_CALL_ABORTED;throw a||this._log.error(`connect failed: ${n}`,e),this.reset(),!a&&!this.isReconnecting&&(v.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(pe.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:B.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new b({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(g.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Ht(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Gi(t,s=>{this._reconnectionTimer=s}),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>=ni()&&this._log.warn(`SDK has tried reconnect for ${ni()} 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(pe.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===ne.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===ne.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ne.FAILED||e.target.connectionState===ne.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===ne.CONNECTED||e.target.connectionState===ne.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(g.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 ft;let e=null;return!Ji()||this._peerConnection.getSenders().length===0?ft:(e=this._peerConnection.getSenders()[0].transport,!ur()||this._peerConnection.getReceivers().length===0?ft:e?e.state:ft)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(ri.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(Wi(s)){let o=e.get(s.localCandidateId),n=e.get(s.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&bc(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let s=d=>{d.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:d})=>{d===this._room&&(clearTimeout(a),n(),t(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(g.LEAVE_SUCCESS,o,this),this.off(ri.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{n();let d=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});vm+=1,og(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Dm=!0,this.emit(ri.FIREWALL_RESTRICTION)),t(d)},Ms);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},T.on(g.LEAVE_SUCCESS,o,this),this.on(ri.CONNECTION_STATE_CHANGED,s,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:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(p=>{var _;return(_=p.ssrcs)==null?void 0:_.find(I=>{var A;return(A=I.value)==null?void 0:A.includes(s)})}),a,d,c;if(n.length===3)a=n[0],d=n[1],c=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[0])),d=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[1])),c=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let p=ku({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ue(this._peerConnection.localDescription.sdp),isDownlink:!0});d=JSON.parse(JSON.stringify(p)),c=JSON.parse(JSON.stringify(p)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let l=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${l}`},{id:e.audio,attribute:"msid",value:`${l}-${h.MAIN} ${l}-audio`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,d.ssrcs=[{id:e.video,attribute:"cname",value:`${l}`},{id:e.video,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${l}`},{id:e.videoRtx,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${l}-aux`;c.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(p=>p.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,d.mid,c.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:o,auxVideo:n}=e;try{if(co()){let a=this._peerConnection.getSenders().slice(0,4);for(let c=0;c<a.length;c++){let l=a[c],m;c===0&&t?m=t:c===1&&s?m=s:c===2&&o?m=o:c===3&&n&&(m=n),m&&(yield this.setSenderMaxBitrate(l,m))}let d=!1;s&&a[1].track&&(d=this.setStartBitrate(1,s)),n&&a[3].track&&(d=this.setStartBitrate(3,n)||d),d&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var s,o;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ue(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp));let a=se?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}]),s&&(n.media[2].bandwidth=[{type:a,limit:se?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:se?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}]);let d={type:"offer",sdp:mt(n)};return this.updateSDP({localDescription:d})}setScaleResolutionDownBy(e,t,s){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(E(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${s} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=mt(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,o)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,s()}catch(d){this._log.error(d),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
83
|
+
${e.map(d=>d.toString()).join(`
|
|
84
|
+
`)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var ti=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(ti||{}),bm=0,Nm=!1,rE=new Set,sE=s=>bm>2&&!Nm&&rE.size===0&&s,oE=1,kt=class extends ym.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"clientAbility");u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"clearConnectTimeout");u(this,"_isSDPLogged",!1);u(this,"enableInsertableStreams",!1);u(this,"insertableStreamsAbortMap",new Map);u(this,"receiverRemoteTrackMap",new WeakMap);u(this,"scriptTransformWorker");u(this,"_isRelayTried",!1);u(this,"_rttOverCount",0);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=y.createLogger({id:`spc${oE++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(vt?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,r;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders?this._serverAbility.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8":"h264"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?pm(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(){Un&&(this.scriptTransformWorker=Cm({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},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}initialize(){return f(this,null,function*(){var t;let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let r=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${r}`),r==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():r==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),v.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):r==="failed"&&v.addFailedEvent({key:521711})},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),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=r=>{let o=new xu(r.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield _m(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:r}=this;!r||(this._log.debug(`dtls state: ${r.state}`),r.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():r.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),v.addSuccessEvent({key:521707}),this.clientAbility}catch(r){throw v.addFailedEvent({key:521707,error:r}),this._log.error(`initialize failed ${r}
|
|
85
|
+
offer: ${e==null?void 0:e.sdp}`),r}})}setPriority(e="high"){if(!!this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,o;try{if(this.currentState==="CONNECTED")return;let n=P(),a={type:"answer",sdp:Em({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(a),yield this.waitForPeerConnectionConnected();let c=((r=this._room.scheduleResult.config)==null?void 0:r.priority)||((o=this._room.joinParams)==null?void 0:o.priority)||new URLSearchParams(location.search).get("priority");c&&this.setPriority(c),t||v.addSuccessEvent({key:521703,cost:P()-n})}catch(n){let a=n instanceof b&&n.code===S.API_CALL_ABORTED;throw a||this._log.error(`connect failed: ${n}`,e),this.reset(),!a&&!this.isReconnecting&&(v.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(pe.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:B.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new b({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(E.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Ft(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Fi(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>=si()&&this._log.warn(`SDK has tried reconnect for ${si()} 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(pe.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===ne.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===ne.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ne.FAILED||e.target.connectionState===ne.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===ne.CONNECTED||e.target.connectionState===ne.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(E.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return ft;let e=null;return!Gi()||this._peerConnection.getSenders().length===0?ft:(e=this._peerConnection.getSenders()[0].transport,!cr()||this._peerConnection.getReceivers().length===0?ft:e?e.state:ft)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(ti.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(Hi(r)){let o=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Nc(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new b({code:S.API_CALL_ABORTED,message:U({key:w.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,o,this),this.off(ti.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});bm+=1,sE(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Nm=!0,this.emit(ti.FIREWALL_RESTRICTION)),t(c)},Ms);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},T.on(E.LEAVE_SUCCESS,o,this),this.on(ti.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(p=>{var _;return(_=p.ssrcs)==null?void 0:_.find(I=>{var A;return(A=I.value)==null?void 0:A.includes(r)})}),a,c,d;if(n.length===3)a=n[0],c=n[1],d=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[0])),c=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[1])),d=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let p=Pu({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ue(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(p)),d=JSON.parse(JSON.stringify(p)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let l=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${l}`},{id:e.audio,attribute:"msid",value:`${l}-${h.MAIN} ${l}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${l}`},{id:e.video,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${l}`},{id:e.videoRtx,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${l}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(p=>p.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(uo()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],m;d===0&&t?m=t:d===1&&r?m=r:d===2&&o?m=o:d===3&&n&&(m=n),m&&(yield this.setSenderMaxBitrate(l,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,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();return(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited"?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=t*1e3,e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ue(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ue(this._peerConnection.remoteDescription.sdp));let a=se?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:se?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:se?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}]);let c={type:"offer",sdp:mt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(g(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=mt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(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)}
|
|
86
86
|
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)}
|
|
87
|
-
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:c,currentDirection:l,direction:m,stopped:p})=>({mid:c,currentDirection:l,direction:m,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(d)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!se||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let s=this._peerConnection.getTransceivers();t.forEach(o=>{s[o].direction!==e&&(s[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===Y.INACTIVE&&n===Y.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Y.SENDONLY&&n===Y.INACTIVE&&(this._parsedAnswer.media[o].direction=Y.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ue(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:Sm(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(s=>{var o;if(s.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=s.payloads)!=null&&o.includes(String(n.payload)))&&(s.fmtp=[],s.payloads="",s.rtp=[],s.rtcpFb=[],yr(s,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 s=!1,o=[];E(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===h.VIDEO){let d;e&&this.is42001fSupported?d=this.clientAbility.video.codecs.find(c=>c.fmtp.includes("42001f")):e||(d=this._serverAbility.video.codecs.find(c=>c.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),d&&!((a=n.payloads)!=null&&a.includes(String(d.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],yr(n,d),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Bt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(s=>t[s])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var l;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let s=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((l=this._room.scheduleResult.config)==null?void 0:l.useTurnTcpInfo)||{};if(!n||!a||!s||!o)return;let d=Math.floor(o/s),c=(this._isRelayTried||d>n)&&o>a;if(!c){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${s} upRTT: ${e} downRTT: ${t} ratio: ${d} over-count: ${this._rttOverCount} isOver: ${c} 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 s=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${s}`);let n=Date.now();yield this.doSwitchRelay(s),this._log.warn(`switchRelay ${s} success`),v.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${s} failed`,n),v.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,s)=>{let o=setTimeout(()=>{this.stopReconnection(),s(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,s).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};N([Kn("reconnect")],Pt.prototype,"startReconnection",1),N([Ii(r=>r.userId)],Pt.prototype,"addDownlink",1),N([Ii(r=>r)],Pt.prototype,"removeDownlink",1),N([Yt(!0)],Pt.prototype,"updateSDP",1),N([Qe(521712,!1)],Pt.prototype,"setOffer",1),N([Qe(521713,!1)],Pt.prototype,"setAnswer",1);var Pu=class{constructor(i){u(this,"tag");u(this,"len");u(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},Lu=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Pu(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},bm=new Set;function br(){let r=Math.floor(Math.random()*4294967296);return bm.has(r)?br():(bm.add(r),r)}var Om=Ce(Pe());var Nr=class extends Om.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_currentState","DISCONNECTED");u(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=y.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(T.emit(g.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 Fo=class extends Nr{constructor(e){super(w(D({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"_flag",0);u(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:d}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:d||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,o=Object.keys(t).find(n=>t[n]!==s[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${s[o]} ${hi()} ${nr()}`),v.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Q.run(Li,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Q.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Gt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&Mi),bigVideo:!!(this.flag&Oi),smallVideo:!!(this.flag&Ds),auxVideo:!!(this.flag&er)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}close(e){var s;let t=((s=this._peerConnection)==null?void 0:s.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var n,a,d;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,s;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),(s=this.singlePC)==null||s.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var c,l,m,p,_,I,A;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264ENCODE})});fe&&ci()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(nt["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let d;if(t&&!s&&t.small&&(d=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_PUBLISH,responseCommand:B.SPC_PUBLISH_RESULT,data:w(D({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:d,isAuxiliary:s}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[s?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:R}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],R,t.streamType)}e&&(this[s?"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:(m=this.localMainVideoTrack)==null?void 0:m.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!s&&(this._room.preferHW||((A=this._room.scheduleResult.config)==null?void 0:A.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){if(!ct())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,d=this._peerConnection.getTransceivers(),c=[],l=[],m=(_,I,A)=>{var $,Me;let R=d[I].sender.replaceTrack(A);l.push(I),($=this.singlePC)!=null&&$.enableInsertableStreams&&R.then(()=>this.createEncodedStreams(d[I].sender,_)),(Me=this.singlePC)!=null&&Me.scriptTransformWorker&&this.initSenderTransfrom(d[I].sender,_),c.push(R)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,o?3:1,n),s&&m(8,2,s);let p=this.singlePC.setTransceiverDirection(Y.SENDONLY,l);return c.push(p),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,d;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let s=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((d=this.getTrackByMediaType(t))!=null&&d.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(c,l)=>{var p;let m=this.getTrackByMediaType(t);if(!m)return l.enqueue(c);(m==null?void 0:m.kind)==="audio"?l.enqueue(m.enableEncodeFrame?m.encodeFrame(c):c):l.enqueue((p=this.singlePC)!=null&&p.isUsingH264?m.encodeFrame(c,t===8):c)}}),o):s.readable).pipeTo(s.writable,o).catch(c=>{this._log.debug("encoded stream error",c),c!=="destory"&&this._log.warn(c)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let s=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:s,isSmall:o}))}enableSmall(e){return f(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Y.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Y.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(D({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(D({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(Y.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Wt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),Gt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Y.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Y.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),Gt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Y.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(s)),o&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:W.UPDATE_MUTE_STAT,responseCommand:B.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(g.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===tr?(this._log.error(Ne.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:U({key:x.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:U({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.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}))})}};N([Ot(function({localVideoTrack:r}){r==null||r.once("6",this.onVideoEncodeFailed,this)})],Fo.prototype,"publish",1),N([Ot(function({localVideoTrack:r}){r==null||r.off("6",this.onVideoEncodeFailed,this)})],Fo.prototype,"unpublish",1);var wu=Fo;function Mm(r){return Object.keys(r).filter(i=>r[i])}var Is=class extends Nr{constructor(e){super(w(D({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"isRobot",!1);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});u(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ci(this._room,this),this.remoteVideoTrack=new Mt(this._room,this),this.remoteAuxiliaryTrack=new ds(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Hi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){var l,m;let t=e.streams[0],{track:s,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let d=h.AUDIO;s.kind===h.VIDEO&&(d=a===h.MAIN?h.VIDEO:h.AUXILIARY);let c=this.remoteAudioTrack;d===h.VIDEO?c=this.remoteVideoTrack:d===h.AUXILIARY&&(c=this.remoteAuxiliaryTrack),(l=this.singlePC)==null||l.receiverRemoteTrackMap.set(o,c),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(o,a,s.kind===h.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(c,o),c.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let s=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:d=>{var l,m;let c=((l=this.singlePC)==null?void 0:l.receiverRemoteTrackMap.get(t))||e;return e.kind===h.AUDIO||(m=this.singlePC)!=null&&m.isUsingH264?c.decodeFrame(d):d}};(e.enableDecodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,c)=>c.enqueue(n.enqueue(d))})):s.readable).pipeTo(s.writable,o).catch(d=>{d!=="destory"&&this._log.warn(d)}),this.singlePC.addAbortController(t,o)}}initReceiverTransform(e,t,s){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:s,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Mm(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ct&&yt<92)return;this.singlePC.startReconnection()}}unsubscribe(s){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=D({},this.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(d=>d===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Mm(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:s,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let d=new b({code:a.code,message:U({key:x.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(!!this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let s={audioSsrc:br(),bigVideoSsrc:br(),bigVideoRtxSsrc:br(),auxVideoSsrc:br(),auxVideoRtxSsrc:br()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:d,auxVideoRtxSsrc:c}=s;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:d,auxiliaryRtx:c},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:B.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:s},retries:3,retryTimeout:0});if(l.data.code!==0)throw new b({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let s=this._room.scheduleResult.config;((s==null?void 0:s.jitterDelay)||(s==null?void 0:s.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:s.jitterDelay,auxDelay:s.jitterDelayAux})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;((e==null?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||mi(e)&&mi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let s=this.singlePC.getReceiversByUserId(this.userId);return te(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),te(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,mi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o}){try{if(e===0&&t===0)return s.forEach(a=>a.jitterBufferTarget=0),o();if(s.forEach(a=>{var m;let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack||mi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(d&&mi(t)||!d&&mi(e))return;let c=d?t||0:e,l=(a.jitterBufferTarget||0)+100;l>c||(a.jitterBufferTarget=l,this._log.debug(`set ${d?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${l} -> ${c}`))}),!s.find(a=>{let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}setAudioJitterBuffer(e){if(!this.singlePC)return;let t=this.singlePC.getReceiversByUserId(this.userId)[0];!t||(this._log.warn(`setAudioJitterBuffer ${e}`),t.jitterBufferTarget=e)}};N([Yt(),j(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new b({code:S.API_CALL_ABORTED,message:U({key:x.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Is.prototype,"subscribe",1),N([Yt()],Is.prototype,"unsubscribe",1),N([Ii(()=>"jitter")],Is.prototype,"setJitterBufferDelay",1);var km=Is;function Pm(){return j(r=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Lm(){return j(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var wm=Ce(Pe());function ag(){return Math.floor(Math.random()*16383)}var xu=class extends wm.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=y.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(B.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",s=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===s&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||ag(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(W.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let o={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${s}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>xu.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let d=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:d})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Gi(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(s){if(t){let d=[...s.cachedMessageMap.values()].sort((c,l)=>c.message.seq-l.message.seq);d[0]&&(o=d[0].message)}s.lastSeq!==0&&o.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${s.lastSeq} -> ${o.seq}`),s.lastSeq=o.seq,clearTimeout((a=s.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=s==null?void 0:s.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},$o=xu;u($o,"SEQ_INTERVAL",300);var{isString:xm,isUndefined:As,getNetworkType:cg,isEmpty:Ho}=He,Lt=class extends wa{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=Zr;this._changeBigSmallRecords=new Map;this.forceRelay=!1;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._updateAudioLevelTaskId=-1;this._stats=new Po(this,this._log),this.userManager=new fa(this.userId,this._log),this._version=Te,this.sdpSemantics=Or,As(e.sdpSemantics)?Jt.isUnifiedPlanDefault()&&(this.sdpSemantics=ki):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${cg()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=As(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Zr,!As(e.enableSPC)&&Zr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Am(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,s){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Fu(n,[]);T.emit(g.REMOTE_PUBLISH_STATE_CHANGED,D({room:this},o)),this.emit("remote-publish-state-changed",D({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,d;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(l){if(l instanceof b&&l.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(l)}let c=P();yield this.doJoin(e,(d=this.singlePC)==null?void 0:d.clientAbility),v.addSuccessEvent({key:521708,cost:P()-c}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(c){v.addFailedEvent({key:521708,error:c}),n(c)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Pt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,o)=>f(this,null,function*(){var d,c,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(pe.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),o(m)}),le((c=(d=this.scheduleResult)==null?void 0:d.config)==null?void 0:c.singlePC)&&Zr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ic(),netType:zr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:S.JOIN_ROOM_FAILED,message:U({key:x.JOIN_ROOM_TIMEOUT})}))},a),T.emit(g.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,n),this.signalChannel.once(B.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:p,message:_,data:I,tinyId:A}=m.data;T.emit(g.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),A&&(this.tinyId=A),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this.singlePC&&this.singlePC.connect(w(D({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new b({code:S.JOIN_ROOM_FAILED,extraCode:p,message:U({key:x.JOIN_ROOM_FAILED,data:{error:_,code:p}})})))})}))}reJoin(e=!0){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(w(D({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Z.logSuccessEvent({userId:this.userId,eventType:We.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(ri.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof wu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(d=>{d.installEvents(),d.onSinglePCReconnected()}))};this.singlePC.on(ri.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ko&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Z.logFailedEvent({userId:this.userId,eventType:We.REJOIN,error:t}),this.emit("error",new b({code:S.JOIN_ROOM_FAILED,message:U({key:x.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||Xh(this.userId),o=!!(s&&s.isConnected&&s.keepAlive),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new _s({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new $o(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ki({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ki.EVENT_NETWORK_QUALITY,a=>{var d;this.emit("network-quality",a),(d=this.singlePC)==null||d.detectTCPAndUDP(a)})),we(this,this.signalChannel).add(pe.CONNECTION_STATE_CHANGED,a=>{T.emit(g.SIGNAL_CONNECTION_STATE_CHANGED,D({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(pe.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(B.PEER_JOIN,a=>{let{srcTinyId:d,userId:c,role:l}=a.data.data;this.userManager.addUser({userId:c,tinyId:d,role:l})}).add(B.PEER_LEAVE,a=>{let{userId:d,reason:c=0}=a.data.data;this.userManager.deleteUser(d,c)}).add(B.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(B.CLIENT_BANNED,a=>{let d=a.data.data,{reason:c}=d;if(Z.uploadEvent({log:`stat-banned:${c}`,userId:this.userId}),c==="user_time_out"){this._log.warn(`${c} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[c==="kick"?"error":"info"](`user was banned because of [${c}]`),this.reset(),this.emit("banned",{reason:c})}),this.signalChannel.once(pe.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(g.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||ge(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(g.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(W.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Q.run(Pi,this.doHeartbeat.bind(this),{delay:2e3}),this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Q.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let s=(n=this.signalChannel)!=null&&n.isConnected?Ah(this.userId):[],o=w(D({str_sdk_version:bs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:D({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:zr()},t.msg_device_info)});if(this.heartbeatReport=o,T.emit(g.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(W.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a}this.emit("heartbeat-report",w(D({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(s=>s.flag!==Ja).map(({userId:s,srcTinyId:o,flag:n})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:s,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:s,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),T.emit(g.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof ko&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s,isRobot:o}){let n=new(this.singlePC?km:Au)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let o=s.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",w(D({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Q.run(Pi,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Q.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:W.GET_USER_LIST,responseCommand:B.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:d,role:c})=>({userId:a,tinyId:d,role:c}));throw U({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.USER_LIST_RES,code:s,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!gu)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)===ne.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof Ge&&!s.getIsReconnecting()){let o=s.getPeerConnection();o&&o.connectionState===ne.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Z.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ko({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let s=new Au({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&(yield s.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield s.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new b({code:S.INVALID_OPERATION,message:U({key:x.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),Q.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:B.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new b({code:S.SWITCH_ROLE_FAILED,message:U({key:x.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof b&&s.getCode()===S.API_CALL_TIMEOUT&&(s=new b({code:S.SWITCH_ROLE_FAILED,message:U({key:x.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return f(this,null,function*(){let t={},s={};e.forEach(d=>{d instanceof Ue&&(d instanceof Kt?s.audio=d:t.audio=d),d instanceof me&&(d instanceof st&&d.mediaType===2?s.video=d:t.video=d)});let o=Ho(t),n=Ho(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new wu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new ko({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",d=>{this.emit("media-connection-state-changed",w(D({},d),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",d=>{let c=d.getCode();c!==S.ICE_TRANSPORT_ERROR&&(c===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",d))}));let a=e.map(d=>d.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Ue&&(o instanceof Kt?s.audio=o:t.audio=o),o instanceof me&&(o instanceof st&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Ho(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Ho(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!Gc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(g.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=D({},s.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),T.emit(g.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Da(n)}] prev: [${Da(s.subscribeState)}]`),yield s.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());T.emit(g.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof b?n.getCode():S.UNKNOWN,d=n;throw n instanceof b?a===S.REMOTE_STREAM_NOT_EXIST&&(d=new b({code:S.API_CALL_ABORTED,message:U({key:x.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(d)):(d=new b({code:a,message:U({key:x.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(d)),d}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),T.emit(g.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,Q.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(g.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Q.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Q.run(Pr,()=>{var o;rd.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){rd.isRunning?n.remoteAudioTrack.volume=0:this.updateDownlinkAudioLevelFromReceiver(n);let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let s=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!s)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=Q.run(Pr,()=>f(this,null,function*(){let a=yield s.getStats();this._updateAudioLevelTaskId<0||a.forEach(d=>{d.type==="media-source"&&d.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=d.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Q.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!Wc||!t)return;let s=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;this._log.debug("updateDownlinkAudioLevelFromReceiver"),s&&(e.remoteAudioTrack.volume=Math.min(s*2,1))}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,s;let e={};return e[this.userId]=((s=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:s.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(He.getTurnServer(o))):He.isPlainObject(e)&&s.push(He.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.START_PUBLISH_TENCENT_CDN_RES:B.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.STOP_PUBLISH_TENCENT_CDN_RES:B.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:B.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.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=He.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:d,reSubscribeCount:c}=a;if(d.video&&t.video||d.smallVideo&&t.smallVideo&&o)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:d.video,smallVideo:d.smallVideo};try{if(!o&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=c-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${Mr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Mr}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${Mr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Mr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(xm(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!As(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:S.INVALID_PARAMETER,message:U({key:x.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!As(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new b({code:S.INVALID_PARAMETER,message:U({key:x.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!As(e.userDefinePushArgs))if(xm(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new b({code:S.INVALID_PARAMETER,message:U({key:x.INVALID_USER_DEFINE_PUSH_ARGS})});Ho(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Dt)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}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 d;let s=t[0].offset,o=t[0].offset;t.forEach(c=>{s=Math.min(c.offset,s),o=Math.max(c.offset,o)});let n=Math.floor(t.reduce((c,l)=>c+l.rtt,0)/t.length),a=Math.floor(t.reduce((c,l)=>c+l.offset,0)/t.length);(o-s>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),Ju(a),(d=this.scriptTransformWorker)==null||d.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:W.UPDATE_NETWORK_TIME,responseCommand:B.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let s=Number(t.data.data.serverSendTime),o=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(o-e+(s-n))/2;return{rtt:n-e-(o-s),offset:a}})}};N([Ou(["left",ce.INIT],"joined"),qe({settings:{retries:1,timeout:0},onRetrying(r){this._log.warn(`join retry ${r}`)},onRetryFailed(r){this._log.error("join failed",r)},onError(r,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),$t(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),i())}}),Gh()],Lt.prototype,"join",1),N([Ou("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Wh(),Kn("leave room"),Eo({fnName:"publish",validateArgs:!1}),Eo({fnName:"unsubscribe",validateArgs:!1})],Lt.prototype,"leave",1),N([Yt(),Pm(),qe({settings:{retries:ni,timeout:r=>Ht(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),T.emit(g.PUBLISH_FAILED,{room:this}))}})],Lt.prototype,"publish",1),N([Eo({fnName:"publish"}),ch("api-call"),Yt(),Lm(),Ot(function(){var r,i;this.localTracks.size===0&&Ji()&&((i=(r=this.singlePC)==null?void 0:r.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],Lt.prototype,"unpublish",1),N([Ii(r=>r.userId)],Lt.prototype,"replaceTrack",1),N([Ii((...r)=>r[0].userId),ra(),Jh(),qe({settings:{retries:ni,timeout:r=>Ht(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),T.emit(g.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Lt.prototype,"subscribe",1),N([Eo({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Ii((...r)=>r[0].userId)],Lt.prototype,"unsubscribe",1);Oo.create=Oo._create.bind(Oo,Lt);var qU=Oo;export{qU as default};
|
|
87
|
+
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:d,currentDirection:l,direction:m,stopped:p})=>({mid:d,currentDirection:l,direction:m,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!se||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===z.INACTIVE&&n===z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===z.SENDONLY&&n===z.INACTIVE&&(this._parsedAnswer.media[o].direction=z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ue(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=gm(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],yr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];g(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===h.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(d=>d.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(d=>d.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],yr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Vt(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 l;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((l=this._room.scheduleResult.config)==null?void 0:l.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),d=(this._isRelayTried||c>n)&&o>a;if(!d){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: ${d} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),v.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};N([Zn("reconnect")],kt.prototype,"startReconnection",1),N([Ti(s=>s.userId)],kt.prototype,"addDownlink",1),N([Ti(s=>s)],kt.prototype,"removeDownlink",1),N([zt(!0)],kt.prototype,"updateSDP",1),N([Xe(521712,!1)],kt.prototype,"setOffer",1),N([Xe(521713,!1)],kt.prototype,"setAnswer",1);var Lu=class{constructor(i){u(this,"tag");u(this,"len");u(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},xu=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Lu(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=2+2+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Rm=new Set;function br(){let s=Math.floor(Math.random()*4294967296);return Rm.has(s)?br():(Rm.add(s),s)}var vm=ye(xe());var Nr=class extends vm.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_currentState","DISCONNECTED");u(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=y.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var Fo=class extends Nr{constructor(e){super(x(D({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"_flag",0);u(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${li()} ${sr()}`),v.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Z.run(ki,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Z.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Ht()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&Di),bigVideo:!!(this.flag&vi),smallVideo:!!(this.flag&Ds),auxVideo:!!(this.flag&Ki)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t,r;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),(r=this.singlePC)==null||r.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var d,l,m,p,_,I,A;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:S.NOT_SUPPORTED_H264,message:U({key:w.NOT_SUPPORTED_H264ENCODE})});fe&&ai()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(nt["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_PUBLISH,responseCommand:B.SPC_PUBLISH_RESULT,data:x(D({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:C}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],C,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(m=this.localMainVideoTrack)==null?void 0:m.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!r&&(this._room.preferHW||((A=this._room.scheduleResult.config)==null?void 0:A.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!ct())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),d=[],l=[],m=(_,I,A)=>{var F,Pe;let C=c[I].sender.replaceTrack(A);l.push(I),(F=this.singlePC)!=null&&F.enableInsertableStreams&&C.then(()=>this.createEncodedStreams(c[I].sender,_)),(Pe=this.singlePC)!=null&&Pe.scriptTransformWorker&&this.initSenderTransfrom(c[I].sender,_),d.push(C)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,o?3:1,n),r&&m(8,2,r);let p=this.singlePC.setTransceiverDirection(z.SENDONLY,l);return d.push(p),Promise.all(d)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(d,l)=>{var p;let m=this.getTrackByMediaType(t);if(!m)return l.enqueue(d);(m==null?void 0:m.kind)==="audio"?l.enqueue(m.enableEncodeFrame?m.encodeFrame(d):d):l.enqueue((p=this.singlePC)!=null&&p.isUsingH264?m.encodeFrame(d,t===8):d)}}),o):r.readable).pipeTo(r.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=x(D({},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=x(D({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(z.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Gt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),Ht()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),Ht()&&(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===h.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} on ${o?h.AUXILIARY:h.MAIN} stream`),r.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:W.UPDATE_MUTE_STAT,responseCommand:B.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Zi?(this._log.error(Ne.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:U({key:w.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:U({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.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}))})}};N([Dt(function({localVideoTrack:s}){s==null||s.once("6",this.onVideoEncodeFailed,this)})],Fo.prototype,"publish",1),N([Dt(function({localVideoTrack:s}){s==null||s.off("6",this.onVideoEncodeFailed,this)})],Fo.prototype,"unpublish",1);var wu=Fo;function Dm(s){return Object.keys(s).filter(i=>s[i])}var Is=class extends Nr{constructor(e){super(x(D({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"isRobot",!1);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});u(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ai(this._room,this),this.remoteVideoTrack=new Ot(this._room,this),this.remoteAuxiliaryTrack=new ds(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return $i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var l,m;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=h.AUDIO;r.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),(l=this.singlePC)==null||l.receiverRemoteTrackMap.set(o,d),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===h.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(r)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let r=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:c=>{var l,m;let d=((l=this.singlePC)==null?void 0:l.receiverRemoteTrackMap.get(t))||e;return e.kind===h.AUDIO||(m=this.singlePC)!=null&&m.isUsingH264?d.decodeFrame(c):c}};(e.enableDecodeFrame?r.readable.pipeThrough(new TransformStream({transform:(c,d)=>d.enqueue(n.enqueue(c))})):r.readable).pipeTo(r.writable,o).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,o)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Dm(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ct&&Rt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=D({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Dm(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:U({key:w.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(!!this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:br(),bigVideoSsrc:br(),bigVideoRtxSsrc:br(),auxVideoSsrc:br(),auxVideoRtxSsrc:br()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:B.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(l.data.code!==0)throw new b({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let r=this._room.scheduleResult.config;((r==null?void 0:r.jitterDelay)||(r==null?void 0:r.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:r.jitterDelay,auxDelay:r.jitterDelayAux})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;((e==null?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||hi(e)&&hi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return ee(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),ee(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,hi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var m;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||hi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&hi(t)||!c&&hi(e))return;let d=c?t||0:e,l=(a.jitterBufferTarget||0)+100;l>d||(a.jitterBufferTarget=l,this._log.debug(`set ${c?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${l} -> ${d}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}setAudioJitterBuffer(e){if(!this.singlePC)return;let t=this.singlePC.getReceiversByUserId(this.userId)[0];!t||(this._log.warn(`setAudioJitterBuffer ${e}`),t.jitterBufferTarget=e)}};N([zt(),j(s=>function(...i){return new Promise((e,t)=>{let r=o=>{this.off("closed",r),t(new b({code:S.API_CALL_ABORTED,message:U({key:w.CONNECTION_ABORTED,data:o})}))};this.on("closed",r),s.apply(this,i).then(e,t).finally(()=>{this.off("closed",r)})})})],Is.prototype,"subscribe",1),N([zt()],Is.prototype,"unsubscribe",1),N([Ti(()=>"jitter")],Is.prototype,"setJitterBufferDelay",1);var Om=Is;function Mm(){return j(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function km(){return j(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Pm=ye(xe());function nE(){return Math.floor(Math.random()*16383)}var Uu=class extends Pm.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=y.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(B.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||nE(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(W.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>Uu.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Fi(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},Ho=Uu;u(Ho,"SEQ_INTERVAL",300);var{isString:Lm,isUndefined:As,getNetworkType:aE,isEmpty:Go}=Fe,Pt=class extends La{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=Kr;this._changeBigSmallRecords=new Map;this.forceRelay=!1;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._updateAudioLevelTaskId=-1;this._stats=new Lo(this,this._log),this.userManager=new pa(this.userId,this._log),this._version=Ie,this.sdpSemantics=Or,As(e.sdpSemantics)?Wt.isUnifiedPlanDefault()&&(this.sdpSemantics=Oi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${aE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=As(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Kr,!As(e.enableSPC)&&Kr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Sm(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Fu(n,[]);T.emit(E.REMOTE_PUBLISH_STATE_CHANGED,D({room:this},o)),this.emit("remote-publish-state-changed",D({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(l){if(l instanceof b&&l.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(l)}let d=P();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:P()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){v.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new kt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(pe.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),o(m)}),le((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Kr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ac(),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;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:S.JOIN_ROOM_FAILED,message:U({key:w.JOIN_ROOM_TIMEOUT})}))},a),T.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,n),this.signalChannel.once(B.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:p,message:_,data:I,tinyId:A}=m.data;T.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),A&&(this.tinyId=A),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this.singlePC&&this.singlePC.connect(x(D({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new b({code:S.JOIN_ROOM_FAILED,extraCode:p,message:U({key:w.JOIN_ROOM_FAILED,data:{error:_,code:p}})})))})}))}reJoin(e=!0){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,r=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,r.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),r.push(this.signalChannel.connect())),yield Promise.all(r),yield this.doJoin(x(D({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),K.logSuccessEvent({userId:this.userId,eventType:Ge.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(ti.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof wu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(ti.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Po&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),K.logFailedEvent({userId:this.userId,eventType:Ge.REJOIN,error:t}),this.emit("error",new b({code:S.JOIN_ROOM_FAILED,message:U({key:w.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||jh(this.userId),o=!!(r&&r.isConnected&&r.keepAlive),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(this.signalChannel=new _s({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Ho(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new zi({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(zi.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Ue(this,this.signalChannel).add(pe.CONNECTION_STATE_CHANGED,a=>{T.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,D({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(pe.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(B.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:l}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:l})}).add(B.PEER_LEAVE,a=>{let{userId:c,reason:d=0}=a.data.data;this.userManager.deleteUser(c,d)}).add(B.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(B.CLIENT_BANNED,a=>{let c=a.data.data,{reason:d}=c;if(K.uploadEvent({log:`stat-banned:${d}`,userId:this.userId}),d==="user_time_out"){this._log.warn(`${d} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[d==="kick"?"error":"info"](`user was banned because of [${d}]`),this.reset(),this.emit("banned",{reason:d})}),this.signalChannel.once(pe.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Ee(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(E.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(W.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),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=Z.run(Mi,this.doHeartbeat.bind(this),{delay:2e3}),this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Z.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Sh(this.userId):[],o=x(D({str_sdk_version:bs,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:D({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Qr()},t.msg_device_info)});if(this.heartbeatReport=o,T.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(W.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a}this.emit("heartbeat-report",x(D({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Ja).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),T.emit(E.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof Po&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?Om:Cu)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",x(D({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Z.run(Mi,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Z.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:W.GET_USER_LIST,responseCommand:B.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw U({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!gu)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)===ne.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof He&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ne.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"),K.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Po({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 Cu({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new b({code:S.INVALID_OPERATION,message:U({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),Z.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:B.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new b({code:S.SWITCH_ROLE_FAILED,message:U({key:w.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof b&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new b({code:S.SWITCH_ROLE_FAILED,message:U({key:w.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Me&&(c instanceof Yt?r.audio=c:t.audio=c),c instanceof me&&(c instanceof rt&&c.mediaType===2?r.video=c:t.video=c)});let o=Go(t),n=Go(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new wu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Po({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",x(D({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==S.ICE_TRANSPORT_ERROR&&(d===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Me&&(o instanceof Yt?r.audio=o:t.audio=o),o instanceof me&&(o instanceof rt&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Go(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Go(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!Jc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=D({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),T.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${va(n)}] prev: [${va(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof b?n.getCode():S.UNKNOWN,c=n;throw n instanceof b?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:S.API_CALL_ABORTED,message:U({key:w.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:U({key:w.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),T.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,Z.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run("intervalInWorker",()=>{var o;lr.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!lr.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=Z.run(Ps,()=>f(this,null,function*(){let a=yield r.getStats();this._updateAudioLevelTaskId<0||a.forEach(c=>{c.type==="media-source"&&c.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=c.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Z.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!jc||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;this._log.debug("updateDownlinkAudioLevelFromReceiver"),ee(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&ee(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(Fe.getTurnServer(o))):Fe.isPlainObject(e)&&r.push(Fe.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.START_PUBLISH_TENCENT_CDN_RES:B.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.STOP_PUBLISH_TENCENT_CDN_RES:B.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:B.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}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=Fe.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${r}] to ${l.smallVideo?"small":"big"} video successfully. count ${Mr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Mr}catch(m){this._log.info(`change [${r}] to ${l.smallVideo?"small":"big"} video failed. count ${Mr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Mr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Lm(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!As(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:S.INVALID_PARAMETER,message:U({key:w.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(!As(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new b({code:S.INVALID_PARAMETER,message:U({key:w.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!As(e.userDefinePushArgs))if(Lm(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new b({code:S.INVALID_PARAMETER,message:U({key:w.INVALID_USER_DEFINE_PUSH_ARGS})});Go(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&vt)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}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,o=t[0].offset;t.forEach(d=>{r=Math.min(d.offset,r),o=Math.max(d.offset,o)});let n=Math.floor(t.reduce((d,l)=>d+l.rtt,0)/t.length),a=Math.floor(t.reduce((d,l)=>d+l.offset,0)/t.length);(o-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),Ju(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:W.UPDATE_NETWORK_TIME,responseCommand:B.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),o=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(o-e+(r-n))/2;return{rtt:n-e-(o-r),offset:a}})}};N([Mu(["left",ce.INIT],"joined"),je({settings:{retries:1,timeout:0},onRetrying(s){this._log.warn(`join retry ${s}`)},onRetryFailed(s){this._log.error("join failed",s)},onError(s,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),$t(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),i())}}),Fh()],Pt.prototype,"join",1),N([Mu("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Hh(),Zn("leave room"),To({fnName:"publish",validateArgs:!1}),To({fnName:"unsubscribe",validateArgs:!1})],Pt.prototype,"leave",1),N([zt(),Mm(),je({settings:{retries:si,timeout:s=>Ft(s)},onError(s,i,e){var t;(t=s.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${s}`),e(s),T.emit(E.PUBLISH_FAILED,{room:this}))}})],Pt.prototype,"publish",1),N([To({fnName:"publish"}),ch("api-call"),zt(),km(),Dt(function(){var s,i;this.localTracks.size===0&&Gi()&&((i=(s=this.singlePC)==null?void 0:s.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],Pt.prototype,"unpublish",1),N([Ti(s=>s.userId)],Pt.prototype,"replaceTrack",1),N([Ti((...s)=>s[0].userId),ia(),Gh(),je({settings:{retries:si,timeout:s=>Ft(s)},onError(s,i,e,t){s.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${s}`),e(s),T.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Pt.prototype,"subscribe",1),N([To({fnName:"subscribe",callback(...s){this.singlePC||s.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Ti((...s)=>s[0].userId)],Pt.prototype,"unsubscribe",1);Mo.create=Mo._create.bind(Mo,Pt);var WU=Mo;export{WU as default};
|