trtc-sdk-v5 5.10.2-beta.14 → 5.10.2-beta.16

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.
Files changed (31) hide show
  1. package/assets/audioProcessor-wasm.js +1 -0
  2. package/assets/debug-dialog.js +2 -2
  3. package/index.d.ts +21 -38
  4. package/package.json +1 -1
  5. package/plugins/cdn-streaming/package.json +1 -1
  6. package/plugins/cross-room/package.json +1 -1
  7. package/plugins/custom-encryption/package.json +1 -1
  8. package/plugins/device-detector/package.json +1 -1
  9. package/plugins/small-stream-auto-switcher/package.json +1 -1
  10. package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.esm.d.ts +0 -1
  11. package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.esm.js +1 -1
  12. package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.umd.js +1 -1
  13. package/plugins/video-decoder/package.json +1 -1
  14. package/plugins/video-decoder/video-decoder.esm.js +1 -1
  15. package/plugins/video-decoder/video-decoder.umd.js +1 -1
  16. package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +1 -1
  17. package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +1 -1
  18. package/plugins/video-effect/basic-beauty/package.json +1 -1
  19. package/plugins/video-effect/beauty/package.json +1 -1
  20. package/plugins/video-effect/virtual-background/package.json +1 -1
  21. package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
  22. package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
  23. package/plugins/video-effect/watermark/package.json +1 -1
  24. package/plugins/voice-changer/package.json +1 -1
  25. package/trtc.esm.js +59 -34
  26. package/trtc.js +17 -1
  27. package/assets/face_detection/blaze_face_short_range.tflite +0 -0
  28. package/assets/face_detection/vision_wasm_internal.gz +0 -0
  29. package/assets/face_detection/vision_wasm_internal.js +0 -20
  30. package/assets/face_detection/vision_wasm_nosimd_internal.gz +0 -0
  31. package/assets/face_detection/vision_wasm_nosimd_internal.js +0 -20
package/trtc.esm.js CHANGED
@@ -1,16 +1,17 @@
1
- var cf=Object.create;var Js=Object.defineProperty,df=Object.defineProperties,Uu=Object.getOwnPropertyDescriptor,lf=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertyNames,pn=Object.getOwnPropertySymbols,Vu=Object.getPrototypeOf,Nc=Object.prototype.hasOwnProperty,Bu=Object.prototype.propertyIsEnumerable,mf=Reflect.get;var Wi=Math.pow,vc=(s,i,e)=>i in s?Js(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,v=(s,i)=>{for(var e in i||(i={}))Nc.call(i,e)&&vc(s,e,i[e]);if(pn)for(var e of pn(i))Bu.call(i,e)&&vc(s,e,i[e]);return s},w=(s,i)=>df(s,lf(i));var Fu=(s,i)=>{var e={};for(var t in s)Nc.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&pn)for(var t of pn(s))i.indexOf(t)<0&&Bu.call(s,t)&&(e[t]=s[t]);return e};var pi=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),fi=(s,i)=>{for(var e in i)Js(s,e,{get:i[e],enumerable:!0})},hf=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of uf(i))!Nc.call(s,r)&&r!==e&&Js(s,r,{get:()=>i[r],enumerable:!(t=Uu(i,r))||t.enumerable});return s};var Be=(s,i,e)=>(e=s!=null?cf(Vu(s)):{},hf(i||!s||!s.__esModule?Js(e,"default",{value:s,enumerable:!0}):e,s));var N=(s,i,e,t)=>{for(var r=t>1?void 0:t?Uu(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&&Js(i,e,r),r};var d=(s,i,e)=>vc(s,typeof i!="symbol"?i+"":i,e);var Fe=(s,i,e)=>mf(Vu(s),e,i);var p=(s,i,e)=>new Promise((t,r)=>{var o=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(s,i)).next())});var Qe=pi((gE,Dc)=>{"use strict";var pf=Object.prototype.hasOwnProperty,ze="~";function js(){}Object.create&&(js.prototype=Object.create(null),new js().__proto__||(ze=!1));function ff(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function $u(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new ff(e,t||s,r),n=ze?ze+i:i;return s._events[n]?s._events[n].fn?s._events[n]=[s._events[n],o]:s._events[n].push(o):(s._events[n]=o,s._eventsCount++),s}function fn(s,i){--s._eventsCount===0?s._events=new js:delete s._events[i]}function $e(){this._events=new js,this._eventsCount=0}$e.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)pf.call(e,t)&&i.push(ze?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};$e.prototype.listeners=function(i){var e=ze?ze+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};$e.prototype.listenerCount=function(i){var e=ze?ze+i:i,t=this._events[e];return t?t.fn?1:t.length:0};$e.prototype.emit=function(i,e,t,r,o,n){var a=ze?ze+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,o),!0;case 6:return c.fn.call(c.context,e,t,r,o,n),!0}for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c.fn.apply(c.context,u)}else{var f=c.length,g;for(m=0;m<f;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),l){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,e);break;case 3:c[m].fn.call(c[m].context,e,t);break;case 4:c[m].fn.call(c[m].context,e,t,r);break;default:if(!u)for(g=1,u=new Array(l-1);g<l;g++)u[g-1]=arguments[g];c[m].fn.apply(c[m].context,u)}}return!0};$e.prototype.on=function(i,e,t){return $u(this,i,e,t,!1)};$e.prototype.once=function(i,e,t){return $u(this,i,e,t,!0)};$e.prototype.removeListener=function(i,e,t,r){var o=ze?ze+i:i;if(!this._events[o])return this;if(!e)return fn(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&fn(this,o);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:fn(this,o)}return this};$e.prototype.removeAllListeners=function(i){var e;return i?(e=ze?ze+i:i,this._events[e]&&fn(this,e)):(this._events=new js,this._eventsCount=0),this};$e.prototype.off=$e.prototype.removeListener;$e.prototype.addListener=$e.prototype.on;$e.prefixed=ze;$e.EventEmitter=$e;typeof Dc!="undefined"&&(Dc.exports=$e)});var sa=pi((SS,vm)=>{"use strict";var bm=vm.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(bm).forEach(function(s){var i=bm[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Om=pi(Ni=>{"use strict";var Ts=function(s){return String(Number(s))===s?Number(s):s},u_=function(s,i,e,t){if(t&&!e)i[t]=Ts(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Ts(s[r+1]))},m_=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;u_(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},Nm=sa(),h_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Ni.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(h_).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<(Nm[o]||[]).length;a+=1){var c=Nm[o][a];if(c.reg.test(n))return m_(c,t,n)}}),i.media=e,i};var Dm=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Ts(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Ni.parseParams=function(s){return s.split(/;\s?/).reduce(Dm,{})};Ni.parseFmtpConfig=Ni.parseParams;Ni.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Ni.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Ts),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(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Dm,{})})};Ni.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Ts(e):(t=Ts(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Mm=pi((AS,km)=>{"use strict";var kd=sa(),p_=/%[sdv%]/g,f_=function(s){var i=1,e=arguments,t=e.length;return s.replace(p_,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""}})},bo=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 f_.apply(null,r)},__=["v","o","s","i","u","e","p","c","b","t","r","z","a"],g_=["i","c","b","a"];km.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||__,t=i.innerOrder||g_,r=[];return e.forEach(function(o){kd[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(bo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(bo(o,n,a))})})}),s.media.forEach(function(o){r.push(bo("m",kd.m[0],o)),t.forEach(function(n){kd[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(bo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(bo(n,a,c))})})})}),r.join(`\r
1
+ var F_=Object.create;var qo=Object.defineProperty,H_=Object.defineProperties,lm=Object.getOwnPropertyDescriptor,G_=Object.getOwnPropertyDescriptors,W_=Object.getOwnPropertyNames,Ca=Object.getOwnPropertySymbols,um=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty,hm=Object.prototype.propertyIsEnumerable,z_=Reflect.get;var Xo=Math.pow,Jc=(s,i,e)=>i in s?qo(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,Z=(s,i)=>{for(var e in i||(i={}))qc.call(i,e)&&Jc(s,e,i[e]);if(Ca)for(var e of Ca(i))hm.call(i,e)&&Jc(s,e,i[e]);return s},de=(s,i)=>H_(s,G_(i));var Qo=(s=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(s,{get:(i,e)=>(typeof require!="undefined"?require:i)[e]}):s)(function(s){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var mm=(s,i)=>{var e={};for(var t in s)qc.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&Ca)for(var t of Ca(s))i.indexOf(t)<0&&hm.call(s,t)&&(e[t]=s[t]);return e};var Oi=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),nr=(s,i)=>{for(var e in i)qo(s,e,{get:i[e],enumerable:!0})},j_=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of W_(i))!qc.call(s,r)&&r!==e&&qo(s,r,{get:()=>i[r],enumerable:!(t=lm(i,r))||t.enumerable});return s};var gt=(s,i,e)=>(e=s!=null?F_(um(s)):{},j_(i||!s||!s.__esModule?qo(e,"default",{value:s,enumerable:!0}):e,s));var J=(s,i,e,t)=>{for(var r=t>1?void 0:t?lm(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&&qo(i,e,r),r};var c=(s,i,e)=>Jc(s,typeof i!="symbol"?i+"":i,e);var Ct=(s,i,e)=>z_(um(s),e,i);var A=(s,i,e)=>new Promise((t,r)=>{var o=d=>{try{a(e.next(d))}catch(l){r(l)}},n=d=>{try{a(e.throw(d))}catch(l){r(l)}},a=d=>d.done?t(d.value):Promise.resolve(d.value).then(o,n);a((e=e.apply(s,i)).next())});var Mt=Oi((ZS,Xc)=>{"use strict";var J_=Object.prototype.hasOwnProperty,wt="~";function Yo(){}Object.create&&(Yo.prototype=Object.create(null),new Yo().__proto__||(wt=!1));function q_(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function pm(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new q_(e,t||s,r),n=wt?wt+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 Ra(s,i){--s._eventsCount===0?s._events=new Yo:delete s._events[i]}function bt(){this._events=new Yo,this._eventsCount=0}bt.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)J_.call(e,t)&&i.push(wt?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};bt.prototype.listeners=function(i){var e=wt?wt+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};bt.prototype.listenerCount=function(i){var e=wt?wt+i:i,t=this._events[e];return t?t.fn?1:t.length:0};bt.prototype.emit=function(i,e,t,r,o,n){var a=wt?wt+i:i;if(!this._events[a])return!1;var d=this._events[a],l=arguments.length,h,u;if(d.fn){switch(d.once&&this.removeListener(i,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,t),!0;case 4:return d.fn.call(d.context,e,t,r),!0;case 5:return d.fn.call(d.context,e,t,r,o),!0;case 6:return d.fn.call(d.context,e,t,r,o,n),!0}for(u=1,h=new Array(l-1);u<l;u++)h[u-1]=arguments[u];d.fn.apply(d.context,h)}else{var m=d.length,p;for(u=0;u<m;u++)switch(d[u].once&&this.removeListener(i,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,e);break;case 3:d[u].fn.call(d[u].context,e,t);break;case 4:d[u].fn.call(d[u].context,e,t,r);break;default:if(!h)for(p=1,h=new Array(l-1);p<l;p++)h[p-1]=arguments[p];d[u].fn.apply(d[u].context,h)}}return!0};bt.prototype.on=function(i,e,t){return pm(this,i,e,t,!1)};bt.prototype.once=function(i,e,t){return pm(this,i,e,t,!0)};bt.prototype.removeListener=function(i,e,t,r){var o=wt?wt+i:i;if(!this._events[o])return this;if(!e)return Ra(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&Ra(this,o);else{for(var a=0,d=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&d.push(n[a]);d.length?this._events[o]=d.length===1?d[0]:d:Ra(this,o)}return this};bt.prototype.removeAllListeners=function(i){var e;return i?(e=wt?wt+i:i,this._events[e]&&Ra(this,e)):(this._events=new Yo,this._eventsCount=0),this};bt.prototype.off=bt.prototype.removeListener;bt.prototype.addListener=bt.prototype.on;bt.prefixed=wt;bt.EventEmitter=bt;typeof Xc!="undefined"&&(Xc.exports=bt)});var md=Oi((tA,ep)=>{"use strict";var Km=ep.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Km).forEach(function(s){var i=Km[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var rp=Oi(Sr=>{"use strict";var _o=function(s){return String(Number(s))===s?Number(s):s},zg=function(s,i,e,t){if(t&&!e)i[t]=_o(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=_o(s[r+1]))},jg=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;zg(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},tp=md(),Jg=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Sr.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(Jg).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<(tp[o]||[]).length;a+=1){var d=tp[o][a];if(d.reg.test(n))return jg(d,t,n)}}),i.media=e,i};var ip=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=_o(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Sr.parseParams=function(s){return s.split(/;\s?/).reduce(ip,{})};Sr.parseFmtpConfig=Sr.parseParams;Sr.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Sr.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(_o),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Sr.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(ip,{})})};Sr.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=_o(e):(t=_o(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var op=Oi((rA,sp)=>{"use strict";var ql=md(),qg=/%[sdv%]/g,Xg=function(s){var i=1,e=arguments,t=e.length;return s.replace(qg,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""}})},Dn=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 Xg.apply(null,r)},Qg=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Yg=["i","c","b","a"];sp.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||Qg,t=i.innerOrder||Yg,r=[];return e.forEach(function(o){ql[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Dn(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Dn(o,n,a))})})}),s.media.forEach(function(o){r.push(Dn("m",ql.m[0],o)),t.forEach(function(n){ql[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Dn(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){r.push(Dn(n,a,d))})})})}),r.join(`\r
2
2
  `)+`\r
3
- `}});var Lm=pi(Zt=>{"use strict";var yr=Om(),T_=Mm(),E_=sa();Zt.grammar=E_;Zt.write=T_;Zt.parse=yr.parse;Zt.parseParams=yr.parseParams;Zt.parseFmtpConfig=yr.parseFmtpConfig;Zt.parsePayloads=yr.parsePayloads;Zt.parseRemoteCandidates=yr.parseRemoteCandidates;Zt.parseImageAttributes=yr.parseImageAttributes;Zt.parseSimulcastStreamList=yr.parseSimulcastStreamList});var Eu=pi((tx,pp)=>{"use strict";var hp=pp.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(hp).forEach(function(s){var i=hp[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var gp=pi($i=>{"use strict";var Bs=function(s){return String(Number(s))===s?Number(s):s},$T=function(s,i,e,t){if(t&&!e)i[t]=Bs(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Bs(s[r+1]))},HT=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;$T(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},fp=Eu(),GT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);$i.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(GT).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<(fp[o]||[]).length;a+=1){var c=fp[o][a];if(c.reg.test(n))return HT(c,t,n)}}),i.media=e,i};var _p=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Bs(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};$i.parseParams=function(s){return s.split(/;\s?/).reduce(_p,{})};$i.parseFmtpConfig=$i.parseParams;$i.parsePayloads=function(s){return s.toString().split(" ").map(Number)};$i.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Bs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};$i.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(_p,{})})};$i.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Bs(e):(t=Bs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Ep=pi((rx,Tp)=>{"use strict";var Su=Eu(),WT=/%[sdv%]/g,JT=function(s){var i=1,e=arguments,t=e.length;return s.replace(WT,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""}})},an=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 JT.apply(null,r)},jT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],qT=["i","c","b","a"];Tp.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||jT,t=i.innerOrder||qT,r=[];return e.forEach(function(o){Su[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(an(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(an(o,n,a))})})}),s.media.forEach(function(o){r.push(an("m",Su.m[0],o)),t.forEach(function(n){Su[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(an(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(an(n,a,c))})})})}),r.join(`\r
3
+ `}});var np=Oi(Fi=>{"use strict";var As=rp(),Zg=op(),Kg=md();Fi.grammar=Kg;Fi.write=Zg;Fi.parse=As.parse;Fi.parseParams=As.parseParams;Fi.parseFmtpConfig=As.parseFmtpConfig;Fi.parsePayloads=As.parsePayloads;Fi.parseRemoteCandidates=As.parseRemoteCandidates;Fi.parseImageAttributes=As.parseImageAttributes;Fi.parseSimulcastStreamList=As.parseSimulcastStreamList});var vf=Oi((bf,wh)=>{"use strict";(function(s){typeof bf=="object"&&typeof wh!="undefined"?wh.exports=s():typeof define=="function"&&define.amd?define([],s):(typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:this).JSZip=s()})(function(){return function s(i,e,t){function r(a,d){if(!e[a]){if(!i[a]){var l=typeof Qo=="function"&&Qo;if(!d&&l)return l(a,!0);if(o)return o(a,!0);var h=new Error("Cannot find module '"+a+"'");throw h.code="MODULE_NOT_FOUND",h}var u=e[a]={exports:{}};i[a][0].call(u.exports,function(m){var p=i[a][1][m];return r(p||m)},u,u.exports,s,i,e,t)}return e[a].exports}for(var o=typeof Qo=="function"&&Qo,n=0;n<t.length;n++)r(t[n]);return r}({1:[function(s,i,e){"use strict";var t=s("./utils"),r=s("./support"),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.encode=function(n){for(var a,d,l,h,u,m,p,g=[],f=0,T=n.length,I=T,v=t.getTypeOf(n)!=="string";f<n.length;)I=T-f,l=v?(a=n[f++],d=f<T?n[f++]:0,f<T?n[f++]:0):(a=n.charCodeAt(f++),d=f<T?n.charCodeAt(f++):0,f<T?n.charCodeAt(f++):0),h=a>>2,u=(3&a)<<4|d>>4,m=1<I?(15&d)<<2|l>>6:64,p=2<I?63&l:64,g.push(o.charAt(h)+o.charAt(u)+o.charAt(m)+o.charAt(p));return g.join("")},e.decode=function(n){var a,d,l,h,u,m,p=0,g=0,f="data:";if(n.substr(0,f.length)===f)throw new Error("Invalid base64 input, it looks like a data url.");var T,I=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===o.charAt(64)&&I--,n.charAt(n.length-2)===o.charAt(64)&&I--,I%1!=0)throw new Error("Invalid base64 input, bad content length.");for(T=r.uint8array?new Uint8Array(0|I):new Array(0|I);p<n.length;)a=o.indexOf(n.charAt(p++))<<2|(h=o.indexOf(n.charAt(p++)))>>4,d=(15&h)<<4|(u=o.indexOf(n.charAt(p++)))>>2,l=(3&u)<<6|(m=o.indexOf(n.charAt(p++))),T[g++]=a,u!==64&&(T[g++]=d),m!==64&&(T[g++]=l);return T}},{"./support":30,"./utils":32}],2:[function(s,i,e){"use strict";var t=s("./external"),r=s("./stream/DataWorker"),o=s("./stream/Crc32Probe"),n=s("./stream/DataLengthProbe");function a(d,l,h,u,m){this.compressedSize=d,this.uncompressedSize=l,this.crc32=h,this.compression=u,this.compressedContent=m}a.prototype={getContentWorker:function(){var d=new r(t.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),l=this;return d.on("end",function(){if(this.streamInfo.data_length!==l.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),d},getCompressedWorker:function(){return new r(t.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(d,l,h){return d.pipe(new o).pipe(new n("uncompressedSize")).pipe(l.compressWorker(h)).pipe(new n("compressedSize")).withStreamInfo("compression",l)},i.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(s,i,e){"use strict";var t=s("./stream/GenericWorker");e.STORE={magic:"\0\0",compressWorker:function(){return new t("STORE compression")},uncompressWorker:function(){return new t("STORE decompression")}},e.DEFLATE=s("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(s,i,e){"use strict";var t=s("./utils"),r=function(){for(var o,n=[],a=0;a<256;a++){o=a;for(var d=0;d<8;d++)o=1&o?3988292384^o>>>1:o>>>1;n[a]=o}return n}();i.exports=function(o,n){return o!==void 0&&o.length?t.getTypeOf(o)!=="string"?function(a,d,l,h){var u=r,m=h+l;a^=-1;for(var p=h;p<m;p++)a=a>>>8^u[255&(a^d[p])];return-1^a}(0|n,o,o.length,0):function(a,d,l,h){var u=r,m=h+l;a^=-1;for(var p=h;p<m;p++)a=a>>>8^u[255&(a^d.charCodeAt(p))];return-1^a}(0|n,o,o.length,0):0}},{"./utils":32}],5:[function(s,i,e){"use strict";e.base64=!1,e.binary=!1,e.dir=!1,e.createFolders=!0,e.date=null,e.compression=null,e.compressionOptions=null,e.comment=null,e.unixPermissions=null,e.dosPermissions=null},{}],6:[function(s,i,e){"use strict";var t=null;t=typeof Promise!="undefined"?Promise:s("lie"),i.exports={Promise:t}},{lie:37}],7:[function(s,i,e){"use strict";var t=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",r=s("pako"),o=s("./utils"),n=s("./stream/GenericWorker"),a=t?"uint8array":"array";function d(l,h){n.call(this,"FlateWorker/"+l),this._pako=null,this._pakoAction=l,this._pakoOptions=h,this.meta={}}e.magic="\b\0",o.inherits(d,n),d.prototype.processChunk=function(l){this.meta=l.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(a,l.data),!1)},d.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},d.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},d.prototype._createPako=function(){this._pako=new r[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var l=this;this._pako.onData=function(h){l.push({data:h,meta:l.meta})}},e.compressWorker=function(l){return new d("Deflate",l)},e.uncompressWorker=function(){return new d("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(s,i,e){"use strict";function t(u,m){var p,g="";for(p=0;p<m;p++)g+=String.fromCharCode(255&u),u>>>=8;return g}function r(u,m,p,g,f,T){var I,v,b=u.file,w=u.compression,N=T!==a.utf8encode,q=o.transformTo("string",T(b.name)),$=o.transformTo("string",a.utf8encode(b.name)),te=b.comment,se=o.transformTo("string",T(te)),y=o.transformTo("string",a.utf8encode(te)),G=$.length!==b.name.length,E=y.length!==te.length,j="",Ce="",O="",Ne=b.dir,ee=b.date,he={crc32:0,compressedSize:0,uncompressedSize:0};m&&!p||(he.crc32=u.crc32,he.compressedSize=u.compressedSize,he.uncompressedSize=u.uncompressedSize);var V=0;m&&(V|=8),N||!G&&!E||(V|=2048);var P=0,_e=0;Ne&&(P|=16),f==="UNIX"?(_e=798,P|=function(oe,st){var yt=oe;return oe||(yt=st?16893:33204),(65535&yt)<<16}(b.unixPermissions,Ne)):(_e=20,P|=function(oe){return 63&(oe||0)}(b.dosPermissions)),I=ee.getUTCHours(),I<<=6,I|=ee.getUTCMinutes(),I<<=5,I|=ee.getUTCSeconds()/2,v=ee.getUTCFullYear()-1980,v<<=4,v|=ee.getUTCMonth()+1,v<<=5,v|=ee.getUTCDate(),G&&(Ce=t(1,1)+t(d(q),4)+$,j+="up"+t(Ce.length,2)+Ce),E&&(O=t(1,1)+t(d(se),4)+y,j+="uc"+t(O.length,2)+O);var ae="";return ae+=`
4
+ \0`,ae+=t(V,2),ae+=w.magic,ae+=t(I,2),ae+=t(v,2),ae+=t(he.crc32,4),ae+=t(he.compressedSize,4),ae+=t(he.uncompressedSize,4),ae+=t(q.length,2),ae+=t(j.length,2),{fileRecord:l.LOCAL_FILE_HEADER+ae+q+j,dirRecord:l.CENTRAL_FILE_HEADER+t(_e,2)+ae+t(se.length,2)+"\0\0\0\0"+t(P,4)+t(g,4)+q+j+se}}var o=s("../utils"),n=s("../stream/GenericWorker"),a=s("../utf8"),d=s("../crc32"),l=s("../signature");function h(u,m,p,g){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=m,this.zipPlatform=p,this.encodeFileName=g,this.streamFiles=u,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(h,n),h.prototype.push=function(u){var m=u.meta.percent||0,p=this.entriesCount,g=this._sources.length;this.accumulate?this.contentBuffer.push(u):(this.bytesWritten+=u.data.length,n.prototype.push.call(this,{data:u.data,meta:{currentFile:this.currentFile,percent:p?(m+100*(p-g-1))/p:100}}))},h.prototype.openedSource=function(u){this.currentSourceOffset=this.bytesWritten,this.currentFile=u.file.name;var m=this.streamFiles&&!u.file.dir;if(m){var p=r(u,m,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(u){this.accumulate=!1;var m=this.streamFiles&&!u.file.dir,p=r(u,m,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),m)this.push({data:function(g){return l.DATA_DESCRIPTOR+t(g.crc32,4)+t(g.compressedSize,4)+t(g.uncompressedSize,4)}(u),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var u=this.bytesWritten,m=0;m<this.dirRecords.length;m++)this.push({data:this.dirRecords[m],meta:{percent:100}});var p=this.bytesWritten-u,g=function(f,T,I,v,b){var w=o.transformTo("string",b(v));return l.CENTRAL_DIRECTORY_END+"\0\0\0\0"+t(f,2)+t(f,2)+t(T,4)+t(I,4)+t(w.length,2)+w}(this.dirRecords.length,p,u,this.zipComment,this.encodeFileName);this.push({data:g,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(u){this._sources.push(u);var m=this;return u.on("data",function(p){m.processChunk(p)}),u.on("end",function(){m.closedSource(m.previous.streamInfo),m._sources.length?m.prepareNextSource():m.end()}),u.on("error",function(p){m.error(p)}),this},h.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(u){var m=this._sources;if(!n.prototype.error.call(this,u))return!1;for(var p=0;p<m.length;p++)try{m[p].error(u)}catch(g){}return!0},h.prototype.lock=function(){n.prototype.lock.call(this);for(var u=this._sources,m=0;m<u.length;m++)u[m].lock()},i.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(s,i,e){"use strict";var t=s("../compressions"),r=s("./ZipFileWorker");e.generateWorker=function(o,n,a){var d=new r(n.streamFiles,a,n.platform,n.encodeFileName),l=0;try{o.forEach(function(h,u){l++;var m=function(T,I){var v=T||I,b=t[v];if(!b)throw new Error(v+" is not a valid compression method !");return b}(u.options.compression,n.compression),p=u.options.compressionOptions||n.compressionOptions||{},g=u.dir,f=u.date;u._compressWorker(m,p).withStreamInfo("file",{name:h,dir:g,date:f,comment:u.comment||"",unixPermissions:u.unixPermissions,dosPermissions:u.dosPermissions}).pipe(d)}),d.entriesCount=l}catch(h){d.error(h)}return d}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(s,i,e){"use strict";function t(){if(!(this instanceof t))return new t;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var r=new t;for(var o in this)typeof this[o]!="function"&&(r[o]=this[o]);return r}}(t.prototype=s("./object")).loadAsync=s("./load"),t.support=s("./support"),t.defaults=s("./defaults"),t.version="3.10.1",t.loadAsync=function(r,o){return new t().loadAsync(r,o)},t.external=s("./external"),i.exports=t},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(s,i,e){"use strict";var t=s("./utils"),r=s("./external"),o=s("./utf8"),n=s("./zipEntries"),a=s("./stream/Crc32Probe"),d=s("./nodejsUtils");function l(h){return new r.Promise(function(u,m){var p=h.decompressed.getContentWorker().pipe(new a);p.on("error",function(g){m(g)}).on("end",function(){p.streamInfo.crc32!==h.decompressed.crc32?m(new Error("Corrupted zip : CRC32 mismatch")):u()}).resume()})}i.exports=function(h,u){var m=this;return u=t.extend(u||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:o.utf8decode}),d.isNode&&d.isStream(h)?r.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):t.prepareContent("the loaded zip file",h,!0,u.optimizedBinaryString,u.base64).then(function(p){var g=new n(u);return g.load(p),g}).then(function(p){var g=[r.Promise.resolve(p)],f=p.files;if(u.checkCRC32)for(var T=0;T<f.length;T++)g.push(l(f[T]));return r.Promise.all(g)}).then(function(p){for(var g=p.shift(),f=g.files,T=0;T<f.length;T++){var I=f[T],v=I.fileNameStr,b=t.resolve(I.fileNameStr);m.file(b,I.decompressed,{binary:!0,optimizedBinaryString:!0,date:I.date,dir:I.dir,comment:I.fileCommentStr.length?I.fileCommentStr:null,unixPermissions:I.unixPermissions,dosPermissions:I.dosPermissions,createFolders:u.createFolders}),I.dir||(m.file(b).unsafeOriginalName=v)}return g.zipComment.length&&(m.comment=g.zipComment),m})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(s,i,e){"use strict";var t=s("../utils"),r=s("../stream/GenericWorker");function o(n,a){r.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(a)}t.inherits(o,r),o.prototype._bindStream=function(n){var a=this;(this._stream=n).pause(),n.on("data",function(d){a.push({data:d,meta:{percent:0}})}).on("error",function(d){a.isPaused?this.generatedError=d:a.error(d)}).on("end",function(){a.isPaused?a._upstreamEnded=!0:a.end()})},o.prototype.pause=function(){return!!r.prototype.pause.call(this)&&(this._stream.pause(),!0)},o.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},i.exports=o},{"../stream/GenericWorker":28,"../utils":32}],13:[function(s,i,e){"use strict";var t=s("readable-stream").Readable;function r(o,n,a){t.call(this,n),this._helper=o;var d=this;o.on("data",function(l,h){d.push(l)||d._helper.pause(),a&&a(h)}).on("error",function(l){d.emit("error",l)}).on("end",function(){d.push(null)})}s("../utils").inherits(r,t),r.prototype._read=function(){this._helper.resume()},i.exports=r},{"../utils":32,"readable-stream":16}],14:[function(s,i,e){"use strict";i.exports={isNode:typeof Buffer!="undefined",newBufferFrom:function(t,r){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(t,r);if(typeof t=="number")throw new Error('The "data" argument must not be a number');return new Buffer(t,r)},allocBuffer:function(t){if(Buffer.alloc)return Buffer.alloc(t);var r=new Buffer(t);return r.fill(0),r},isBuffer:function(t){return Buffer.isBuffer(t)},isStream:function(t){return t&&typeof t.on=="function"&&typeof t.pause=="function"&&typeof t.resume=="function"}}},{}],15:[function(s,i,e){"use strict";function t(b,w,N){var q,$=o.getTypeOf(w),te=o.extend(N||{},d);te.date=te.date||new Date,te.compression!==null&&(te.compression=te.compression.toUpperCase()),typeof te.unixPermissions=="string"&&(te.unixPermissions=parseInt(te.unixPermissions,8)),te.unixPermissions&&16384&te.unixPermissions&&(te.dir=!0),te.dosPermissions&&16&te.dosPermissions&&(te.dir=!0),te.dir&&(b=f(b)),te.createFolders&&(q=g(b))&&T.call(this,q,!0);var se=$==="string"&&te.binary===!1&&te.base64===!1;N&&N.binary!==void 0||(te.binary=!se),(w instanceof l&&w.uncompressedSize===0||te.dir||!w||w.length===0)&&(te.base64=!1,te.binary=!0,w="",te.compression="STORE",$="string");var y=null;y=w instanceof l||w instanceof n?w:m.isNode&&m.isStream(w)?new p(b,w):o.prepareContent(b,w,te.binary,te.optimizedBinaryString,te.base64);var G=new h(b,y,te);this.files[b]=G}var r=s("./utf8"),o=s("./utils"),n=s("./stream/GenericWorker"),a=s("./stream/StreamHelper"),d=s("./defaults"),l=s("./compressedObject"),h=s("./zipObject"),u=s("./generate"),m=s("./nodejsUtils"),p=s("./nodejs/NodejsStreamInputAdapter"),g=function(b){b.slice(-1)==="/"&&(b=b.substring(0,b.length-1));var w=b.lastIndexOf("/");return 0<w?b.substring(0,w):""},f=function(b){return b.slice(-1)!=="/"&&(b+="/"),b},T=function(b,w){return w=w!==void 0?w:d.createFolders,b=f(b),this.files[b]||t.call(this,b,null,{dir:!0,createFolders:w}),this.files[b]};function I(b){return Object.prototype.toString.call(b)==="[object RegExp]"}var v={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(b){var w,N,q;for(w in this.files)q=this.files[w],(N=w.slice(this.root.length,w.length))&&w.slice(0,this.root.length)===this.root&&b(N,q)},filter:function(b){var w=[];return this.forEach(function(N,q){b(N,q)&&w.push(q)}),w},file:function(b,w,N){if(arguments.length!==1)return b=this.root+b,t.call(this,b,w,N),this;if(I(b)){var q=b;return this.filter(function(te,se){return!se.dir&&q.test(te)})}var $=this.files[this.root+b];return $&&!$.dir?$:null},folder:function(b){if(!b)return this;if(I(b))return this.filter(function($,te){return te.dir&&b.test($)});var w=this.root+b,N=T.call(this,w),q=this.clone();return q.root=N.name,q},remove:function(b){b=this.root+b;var w=this.files[b];if(w||(b.slice(-1)!=="/"&&(b+="/"),w=this.files[b]),w&&!w.dir)delete this.files[b];else for(var N=this.filter(function($,te){return te.name.slice(0,b.length)===b}),q=0;q<N.length;q++)delete this.files[N[q].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(b){var w,N={};try{if((N=o.extend(b||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:r.utf8encode})).type=N.type.toLowerCase(),N.compression=N.compression.toUpperCase(),N.type==="binarystring"&&(N.type="string"),!N.type)throw new Error("No output type specified.");o.checkSupport(N.type),N.platform!=="darwin"&&N.platform!=="freebsd"&&N.platform!=="linux"&&N.platform!=="sunos"||(N.platform="UNIX"),N.platform==="win32"&&(N.platform="DOS");var q=N.comment||this.comment||"";w=u.generateWorker(this,N,q)}catch($){(w=new n("error")).error($)}return new a(w,N.type||"string",N.mimeType)},generateAsync:function(b,w){return this.generateInternalStream(b).accumulate(w)},generateNodeStream:function(b,w){return(b=b||{}).type||(b.type="nodebuffer"),this.generateInternalStream(b).toNodejsStream(w)}};i.exports=v},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(s,i,e){"use strict";i.exports=s("stream")},{stream:void 0}],17:[function(s,i,e){"use strict";var t=s("./DataReader");function r(o){t.call(this,o);for(var n=0;n<this.data.length;n++)o[n]=255&o[n]}s("../utils").inherits(r,t),r.prototype.byteAt=function(o){return this.data[this.zero+o]},r.prototype.lastIndexOfSignature=function(o){for(var n=o.charCodeAt(0),a=o.charCodeAt(1),d=o.charCodeAt(2),l=o.charCodeAt(3),h=this.length-4;0<=h;--h)if(this.data[h]===n&&this.data[h+1]===a&&this.data[h+2]===d&&this.data[h+3]===l)return h-this.zero;return-1},r.prototype.readAndCheckSignature=function(o){var n=o.charCodeAt(0),a=o.charCodeAt(1),d=o.charCodeAt(2),l=o.charCodeAt(3),h=this.readData(4);return n===h[0]&&a===h[1]&&d===h[2]&&l===h[3]},r.prototype.readData=function(o){if(this.checkOffset(o),o===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,n},i.exports=r},{"../utils":32,"./DataReader":18}],18:[function(s,i,e){"use strict";var t=s("../utils");function r(o){this.data=o,this.length=o.length,this.index=0,this.zero=0}r.prototype={checkOffset:function(o){this.checkIndex(this.index+o)},checkIndex:function(o){if(this.length<this.zero+o||o<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+o+"). Corrupted zip ?")},setIndex:function(o){this.checkIndex(o),this.index=o},skip:function(o){this.setIndex(this.index+o)},byteAt:function(){},readInt:function(o){var n,a=0;for(this.checkOffset(o),n=this.index+o-1;n>=this.index;n--)a=(a<<8)+this.byteAt(n);return this.index+=o,a},readString:function(o){return t.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},i.exports=r},{"../utils":32}],19:[function(s,i,e){"use strict";var t=s("./Uint8ArrayReader");function r(o){t.call(this,o)}s("../utils").inherits(r,t),r.prototype.readData=function(o){this.checkOffset(o);var n=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,n},i.exports=r},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(s,i,e){"use strict";var t=s("./DataReader");function r(o){t.call(this,o)}s("../utils").inherits(r,t),r.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},r.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},r.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},r.prototype.readData=function(o){this.checkOffset(o);var n=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,n},i.exports=r},{"../utils":32,"./DataReader":18}],21:[function(s,i,e){"use strict";var t=s("./ArrayReader");function r(o){t.call(this,o)}s("../utils").inherits(r,t),r.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,n},i.exports=r},{"../utils":32,"./ArrayReader":17}],22:[function(s,i,e){"use strict";var t=s("../utils"),r=s("../support"),o=s("./ArrayReader"),n=s("./StringReader"),a=s("./NodeBufferReader"),d=s("./Uint8ArrayReader");i.exports=function(l){var h=t.getTypeOf(l);return t.checkSupport(h),h!=="string"||r.uint8array?h==="nodebuffer"?new a(l):r.uint8array?new d(t.transformTo("uint8array",l)):new o(t.transformTo("array",l)):new n(l)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(s,i,e){"use strict";e.LOCAL_FILE_HEADER="PK",e.CENTRAL_FILE_HEADER="PK",e.CENTRAL_DIRECTORY_END="PK",e.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",e.ZIP64_CENTRAL_DIRECTORY_END="PK",e.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(s,i,e){"use strict";var t=s("./GenericWorker"),r=s("../utils");function o(n){t.call(this,"ConvertWorker to "+n),this.destType=n}r.inherits(o,t),o.prototype.processChunk=function(n){this.push({data:r.transformTo(this.destType,n.data),meta:n.meta})},i.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(s,i,e){"use strict";var t=s("./GenericWorker"),r=s("../crc32");function o(){t.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}s("../utils").inherits(o,t),o.prototype.processChunk=function(n){this.streamInfo.crc32=r(n.data,this.streamInfo.crc32||0),this.push(n)},i.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(s,i,e){"use strict";var t=s("../utils"),r=s("./GenericWorker");function o(n){r.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}t.inherits(o,r),o.prototype.processChunk=function(n){if(n){var a=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=a+n.data.length}r.prototype.processChunk.call(this,n)},i.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(s,i,e){"use strict";var t=s("../utils"),r=s("./GenericWorker");function o(n){r.call(this,"DataWorker");var a=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(d){a.dataIsReady=!0,a.data=d,a.max=d&&d.length||0,a.type=t.getTypeOf(d),a.isPaused||a._tickAndRepeat()},function(d){a.error(d)})}t.inherits(o,r),o.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,t.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(t.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,a=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,a);break;case"uint8array":n=this.data.subarray(this.index,a);break;case"array":case"nodebuffer":n=this.data.slice(this.index,a)}return this.index=a,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(s,i,e){"use strict";function t(r){this.name=r||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}t.prototype={push:function(r){this.emit("data",r)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(r){this.emit("error",r)}return!0},error:function(r){return!this.isFinished&&(this.isPaused?this.generatedError=r:(this.isFinished=!0,this.emit("error",r),this.previous&&this.previous.error(r),this.cleanUp()),!0)},on:function(r,o){return this._listeners[r].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(r,o){if(this._listeners[r])for(var n=0;n<this._listeners[r].length;n++)this._listeners[r][n].call(this,o)},pipe:function(r){return r.registerPrevious(this)},registerPrevious:function(r){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=r.streamInfo,this.mergeStreamInfo(),this.previous=r;var o=this;return r.on("data",function(n){o.processChunk(n)}),r.on("end",function(){o.end()}),r.on("error",function(n){o.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var r=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),r=!0),this.previous&&this.previous.resume(),!r},flush:function(){},processChunk:function(r){this.push(r)},withStreamInfo:function(r,o){return this.extraStreamInfo[r]=o,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var r in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,r)&&(this.streamInfo[r]=this.extraStreamInfo[r])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var r="Worker "+this.name;return this.previous?this.previous+" -> "+r:r}},i.exports=t},{}],29:[function(s,i,e){"use strict";var t=s("../utils"),r=s("./ConvertWorker"),o=s("./GenericWorker"),n=s("../base64"),a=s("../support"),d=s("../external"),l=null;if(a.nodestream)try{l=s("../nodejs/NodejsStreamOutputAdapter")}catch(m){}function h(m,p){return new d.Promise(function(g,f){var T=[],I=m._internalType,v=m._outputType,b=m._mimeType;m.on("data",function(w,N){T.push(w),p&&p(N)}).on("error",function(w){T=[],f(w)}).on("end",function(){try{var w=function(N,q,$){switch(N){case"blob":return t.newBlob(t.transformTo("arraybuffer",q),$);case"base64":return n.encode(q);default:return t.transformTo(N,q)}}(v,function(N,q){var $,te=0,se=null,y=0;for($=0;$<q.length;$++)y+=q[$].length;switch(N){case"string":return q.join("");case"array":return Array.prototype.concat.apply([],q);case"uint8array":for(se=new Uint8Array(y),$=0;$<q.length;$++)se.set(q[$],te),te+=q[$].length;return se;case"nodebuffer":return Buffer.concat(q);default:throw new Error("concat : unsupported type '"+N+"'")}}(I,T),b);g(w)}catch(N){f(N)}T=[]}).resume()})}function u(m,p,g){var f=p;switch(p){case"blob":case"arraybuffer":f="uint8array";break;case"base64":f="string"}try{this._internalType=f,this._outputType=p,this._mimeType=g,t.checkSupport(f),this._worker=m.pipe(new r(f)),m.lock()}catch(T){this._worker=new o("error"),this._worker.error(T)}}u.prototype={accumulate:function(m){return h(this,m)},on:function(m,p){var g=this;return m==="data"?this._worker.on(m,function(f){p.call(g,f.data,f.meta)}):this._worker.on(m,function(){t.delay(p,arguments,g)}),this},resume:function(){return t.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(m){if(t.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new l(this,{objectMode:this._outputType!=="nodebuffer"},m)}},i.exports=u},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(s,i,e){"use strict";if(e.base64=!0,e.array=!0,e.string=!0,e.arraybuffer=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined",e.nodebuffer=typeof Buffer!="undefined",e.uint8array=typeof Uint8Array!="undefined",typeof ArrayBuffer=="undefined")e.blob=!1;else{var t=new ArrayBuffer(0);try{e.blob=new Blob([t],{type:"application/zip"}).size===0}catch(o){try{var r=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);r.append(t),e.blob=r.getBlob("application/zip").size===0}catch(n){e.blob=!1}}}try{e.nodestream=!!s("readable-stream").Readable}catch(o){e.nodestream=!1}},{"readable-stream":16}],31:[function(s,i,e){"use strict";for(var t=s("./utils"),r=s("./support"),o=s("./nodejsUtils"),n=s("./stream/GenericWorker"),a=new Array(256),d=0;d<256;d++)a[d]=252<=d?6:248<=d?5:240<=d?4:224<=d?3:192<=d?2:1;a[254]=a[254]=1;function l(){n.call(this,"utf-8 decode"),this.leftOver=null}function h(){n.call(this,"utf-8 encode")}e.utf8encode=function(u){return r.nodebuffer?o.newBufferFrom(u,"utf-8"):function(m){var p,g,f,T,I,v=m.length,b=0;for(T=0;T<v;T++)(64512&(g=m.charCodeAt(T)))==55296&&T+1<v&&(64512&(f=m.charCodeAt(T+1)))==56320&&(g=65536+(g-55296<<10)+(f-56320),T++),b+=g<128?1:g<2048?2:g<65536?3:4;for(p=r.uint8array?new Uint8Array(b):new Array(b),T=I=0;I<b;T++)(64512&(g=m.charCodeAt(T)))==55296&&T+1<v&&(64512&(f=m.charCodeAt(T+1)))==56320&&(g=65536+(g-55296<<10)+(f-56320),T++),g<128?p[I++]=g:(g<2048?p[I++]=192|g>>>6:(g<65536?p[I++]=224|g>>>12:(p[I++]=240|g>>>18,p[I++]=128|g>>>12&63),p[I++]=128|g>>>6&63),p[I++]=128|63&g);return p}(u)},e.utf8decode=function(u){return r.nodebuffer?t.transformTo("nodebuffer",u).toString("utf-8"):function(m){var p,g,f,T,I=m.length,v=new Array(2*I);for(p=g=0;p<I;)if((f=m[p++])<128)v[g++]=f;else if(4<(T=a[f]))v[g++]=65533,p+=T-1;else{for(f&=T===2?31:T===3?15:7;1<T&&p<I;)f=f<<6|63&m[p++],T--;1<T?v[g++]=65533:f<65536?v[g++]=f:(f-=65536,v[g++]=55296|f>>10&1023,v[g++]=56320|1023&f)}return v.length!==g&&(v.subarray?v=v.subarray(0,g):v.length=g),t.applyFromCharCode(v)}(u=t.transformTo(r.uint8array?"uint8array":"array",u))},t.inherits(l,n),l.prototype.processChunk=function(u){var m=t.transformTo(r.uint8array?"uint8array":"array",u.data);if(this.leftOver&&this.leftOver.length){if(r.uint8array){var p=m;(m=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),m.set(p,this.leftOver.length)}else m=this.leftOver.concat(m);this.leftOver=null}var g=function(T,I){var v;for((I=I||T.length)>T.length&&(I=T.length),v=I-1;0<=v&&(192&T[v])==128;)v--;return v<0||v===0?I:v+a[T[v]]>I?v:I}(m),f=m;g!==m.length&&(r.uint8array?(f=m.subarray(0,g),this.leftOver=m.subarray(g,m.length)):(f=m.slice(0,g),this.leftOver=m.slice(g,m.length))),this.push({data:e.utf8decode(f),meta:u.meta})},l.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:e.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},e.Utf8DecodeWorker=l,t.inherits(h,n),h.prototype.processChunk=function(u){this.push({data:e.utf8encode(u.data),meta:u.meta})},e.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(s,i,e){"use strict";var t=s("./support"),r=s("./base64"),o=s("./nodejsUtils"),n=s("./external");function a(p){return p}function d(p,g){for(var f=0;f<p.length;++f)g[f]=255&p.charCodeAt(f);return g}s("setimmediate"),e.newBlob=function(p,g){e.checkSupport("blob");try{return new Blob([p],{type:g})}catch(T){try{var f=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return f.append(p),f.getBlob(g)}catch(I){throw new Error("Bug : can't construct the Blob.")}}};var l={stringifyByChunk:function(p,g,f){var T=[],I=0,v=p.length;if(v<=f)return String.fromCharCode.apply(null,p);for(;I<v;)g==="array"||g==="nodebuffer"?T.push(String.fromCharCode.apply(null,p.slice(I,Math.min(I+f,v)))):T.push(String.fromCharCode.apply(null,p.subarray(I,Math.min(I+f,v)))),I+=f;return T.join("")},stringifyByChar:function(p){for(var g="",f=0;f<p.length;f++)g+=String.fromCharCode(p[f]);return g},applyCanBeUsed:{uint8array:function(){try{return t.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch(p){return!1}}(),nodebuffer:function(){try{return t.nodebuffer&&String.fromCharCode.apply(null,o.allocBuffer(1)).length===1}catch(p){return!1}}()}};function h(p){var g=65536,f=e.getTypeOf(p),T=!0;if(f==="uint8array"?T=l.applyCanBeUsed.uint8array:f==="nodebuffer"&&(T=l.applyCanBeUsed.nodebuffer),T)for(;1<g;)try{return l.stringifyByChunk(p,f,g)}catch(I){g=Math.floor(g/2)}return l.stringifyByChar(p)}function u(p,g){for(var f=0;f<p.length;f++)g[f]=p[f];return g}e.applyFromCharCode=h;var m={};m.string={string:a,array:function(p){return d(p,new Array(p.length))},arraybuffer:function(p){return m.string.uint8array(p).buffer},uint8array:function(p){return d(p,new Uint8Array(p.length))},nodebuffer:function(p){return d(p,o.allocBuffer(p.length))}},m.array={string:h,array:a,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return o.newBufferFrom(p)}},m.arraybuffer={string:function(p){return h(new Uint8Array(p))},array:function(p){return u(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:a,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return o.newBufferFrom(new Uint8Array(p))}},m.uint8array={string:h,array:function(p){return u(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:a,nodebuffer:function(p){return o.newBufferFrom(p)}},m.nodebuffer={string:h,array:function(p){return u(p,new Array(p.length))},arraybuffer:function(p){return m.nodebuffer.uint8array(p).buffer},uint8array:function(p){return u(p,new Uint8Array(p.length))},nodebuffer:a},e.transformTo=function(p,g){if(g=g||"",!p)return g;e.checkSupport(p);var f=e.getTypeOf(g);return m[f][p](g)},e.resolve=function(p){for(var g=p.split("/"),f=[],T=0;T<g.length;T++){var I=g[T];I==="."||I===""&&T!==0&&T!==g.length-1||(I===".."?f.pop():f.push(I))}return f.join("/")},e.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":t.nodebuffer&&o.isBuffer(p)?"nodebuffer":t.uint8array&&p instanceof Uint8Array?"uint8array":t.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},e.checkSupport=function(p){if(!t[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},e.MAX_VALUE_16BITS=65535,e.MAX_VALUE_32BITS=-1,e.pretty=function(p){var g,f,T="";for(f=0;f<(p||"").length;f++)T+="\\x"+((g=p.charCodeAt(f))<16?"0":"")+g.toString(16).toUpperCase();return T},e.delay=function(p,g,f){setImmediate(function(){p.apply(f||null,g||[])})},e.inherits=function(p,g){function f(){}f.prototype=g.prototype,p.prototype=new f},e.extend=function(){var p,g,f={};for(p=0;p<arguments.length;p++)for(g in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],g)&&f[g]===void 0&&(f[g]=arguments[p][g]);return f},e.prepareContent=function(p,g,f,T,I){return n.Promise.resolve(g).then(function(v){return t.blob&&(v instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(v))!==-1)&&typeof FileReader!="undefined"?new n.Promise(function(b,w){var N=new FileReader;N.onload=function(q){b(q.target.result)},N.onerror=function(q){w(q.target.error)},N.readAsArrayBuffer(v)}):v}).then(function(v){var b=e.getTypeOf(v);return b?(b==="arraybuffer"?v=e.transformTo("uint8array",v):b==="string"&&(I?v=r.decode(v):f&&T!==!0&&(v=function(w){return d(w,t.uint8array?new Uint8Array(w.length):new Array(w.length))}(v))),v):n.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(s,i,e){"use strict";var t=s("./reader/readerFor"),r=s("./utils"),o=s("./signature"),n=s("./zipEntry"),a=s("./support");function d(l){this.files=[],this.loadOptions=l}d.prototype={checkSignature:function(l){if(!this.reader.readAndCheckSignature(l)){this.reader.index-=4;var h=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+r.pretty(h)+", expected "+r.pretty(l)+")")}},isSignature:function(l,h){var u=this.reader.index;this.reader.setIndex(l);var m=this.reader.readString(4)===h;return this.reader.setIndex(u),m},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var l=this.reader.readData(this.zipCommentLength),h=a.uint8array?"uint8array":"array",u=r.transformTo(h,l);this.zipComment=this.loadOptions.decodeFileName(u)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var l,h,u,m=this.zip64EndOfCentralSize-44;0<m;)l=this.reader.readInt(2),h=this.reader.readInt(4),u=this.reader.readData(h),this.zip64ExtensibleData[l]={id:l,length:h,value:u}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var l,h;for(l=0;l<this.files.length;l++)h=this.files[l],this.reader.setIndex(h.localHeaderOffset),this.checkSignature(o.LOCAL_FILE_HEADER),h.readLocalPart(this.reader),h.handleUTF8(),h.processAttributes()},readCentralDir:function(){var l;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(o.CENTRAL_FILE_HEADER);)(l=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(l);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var l=this.reader.lastIndexOfSignature(o.CENTRAL_DIRECTORY_END);if(l<0)throw this.isSignature(0,o.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(l);var h=l;if(this.checkSignature(o.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===r.MAX_VALUE_16BITS||this.diskWithCentralDirStart===r.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===r.MAX_VALUE_16BITS||this.centralDirRecords===r.MAX_VALUE_16BITS||this.centralDirSize===r.MAX_VALUE_32BITS||this.centralDirOffset===r.MAX_VALUE_32BITS){if(this.zip64=!0,(l=this.reader.lastIndexOfSignature(o.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(l),this.checkSignature(o.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,o.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(o.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(o.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var u=this.centralDirOffset+this.centralDirSize;this.zip64&&(u+=20,u+=12+this.zip64EndOfCentralSize);var m=h-u;if(0<m)this.isSignature(h,o.CENTRAL_FILE_HEADER)||(this.reader.zero=m);else if(m<0)throw new Error("Corrupted zip: missing "+Math.abs(m)+" bytes.")},prepareReader:function(l){this.reader=t(l)},load:function(l){this.prepareReader(l),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},i.exports=d},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(s,i,e){"use strict";var t=s("./reader/readerFor"),r=s("./utils"),o=s("./compressedObject"),n=s("./crc32"),a=s("./utf8"),d=s("./compressions"),l=s("./support");function h(u,m){this.options=u,this.loadOptions=m}h.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(u){var m,p;if(u.skip(22),this.fileNameLength=u.readInt(2),p=u.readInt(2),this.fileName=u.readData(this.fileNameLength),u.skip(p),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((m=function(g){for(var f in d)if(Object.prototype.hasOwnProperty.call(d,f)&&d[f].magic===g)return d[f];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+r.pretty(this.compressionMethod)+" unknown (inner file : "+r.transformTo("string",this.fileName)+")");this.decompressed=new o(this.compressedSize,this.uncompressedSize,this.crc32,m,u.readData(this.compressedSize))},readCentralPart:function(u){this.versionMadeBy=u.readInt(2),u.skip(2),this.bitFlag=u.readInt(2),this.compressionMethod=u.readString(2),this.date=u.readDate(),this.crc32=u.readInt(4),this.compressedSize=u.readInt(4),this.uncompressedSize=u.readInt(4);var m=u.readInt(2);if(this.extraFieldsLength=u.readInt(2),this.fileCommentLength=u.readInt(2),this.diskNumberStart=u.readInt(2),this.internalFileAttributes=u.readInt(2),this.externalFileAttributes=u.readInt(4),this.localHeaderOffset=u.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");u.skip(m),this.readExtraFields(u),this.parseZIP64ExtraField(u),this.fileComment=u.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var u=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),u==0&&(this.dosPermissions=63&this.externalFileAttributes),u==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var u=t(this.extraFields[1].value);this.uncompressedSize===r.MAX_VALUE_32BITS&&(this.uncompressedSize=u.readInt(8)),this.compressedSize===r.MAX_VALUE_32BITS&&(this.compressedSize=u.readInt(8)),this.localHeaderOffset===r.MAX_VALUE_32BITS&&(this.localHeaderOffset=u.readInt(8)),this.diskNumberStart===r.MAX_VALUE_32BITS&&(this.diskNumberStart=u.readInt(4))}},readExtraFields:function(u){var m,p,g,f=u.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});u.index+4<f;)m=u.readInt(2),p=u.readInt(2),g=u.readData(p),this.extraFields[m]={id:m,length:p,value:g};u.setIndex(f)},handleUTF8:function(){var u=l.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var m=this.findExtraFieldUnicodePath();if(m!==null)this.fileNameStr=m;else{var p=r.transformTo(u,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var g=this.findExtraFieldUnicodeComment();if(g!==null)this.fileCommentStr=g;else{var f=r.transformTo(u,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(f)}}},findExtraFieldUnicodePath:function(){var u=this.extraFields[28789];if(u){var m=t(u.value);return m.readInt(1)!==1||n(this.fileName)!==m.readInt(4)?null:a.utf8decode(m.readData(u.length-5))}return null},findExtraFieldUnicodeComment:function(){var u=this.extraFields[25461];if(u){var m=t(u.value);return m.readInt(1)!==1||n(this.fileComment)!==m.readInt(4)?null:a.utf8decode(m.readData(u.length-5))}return null}},i.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(s,i,e){"use strict";function t(m,p,g){this.name=m,this.dir=g.dir,this.date=g.date,this.comment=g.comment,this.unixPermissions=g.unixPermissions,this.dosPermissions=g.dosPermissions,this._data=p,this._dataBinary=g.binary,this.options={compression:g.compression,compressionOptions:g.compressionOptions}}var r=s("./stream/StreamHelper"),o=s("./stream/DataWorker"),n=s("./utf8"),a=s("./compressedObject"),d=s("./stream/GenericWorker");t.prototype={internalStream:function(m){var p=null,g="string";try{if(!m)throw new Error("No output type specified.");var f=(g=m.toLowerCase())==="string"||g==="text";g!=="binarystring"&&g!=="text"||(g="string"),p=this._decompressWorker();var T=!this._dataBinary;T&&!f&&(p=p.pipe(new n.Utf8EncodeWorker)),!T&&f&&(p=p.pipe(new n.Utf8DecodeWorker))}catch(I){(p=new d("error")).error(I)}return new r(p,g,"")},async:function(m,p){return this.internalStream(m).accumulate(p)},nodeStream:function(m,p){return this.internalStream(m||"nodebuffer").toNodejsStream(p)},_compressWorker:function(m,p){if(this._data instanceof a&&this._data.compression.magic===m.magic)return this._data.getCompressedWorker();var g=this._decompressWorker();return this._dataBinary||(g=g.pipe(new n.Utf8EncodeWorker)),a.createWorkerFrom(g,m,p)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof d?this._data:new o(this._data)}};for(var l=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<l.length;u++)t.prototype[l[u]]=h;i.exports=t},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(s,i,e){(function(t){"use strict";var r,o,n=t.MutationObserver||t.WebKitMutationObserver;if(n){var a=0,d=new n(m),l=t.document.createTextNode("");d.observe(l,{characterData:!0}),r=function(){l.data=a=++a%2}}else if(t.setImmediate||t.MessageChannel===void 0)r="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var p=t.document.createElement("script");p.onreadystatechange=function(){m(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},t.document.documentElement.appendChild(p)}:function(){setTimeout(m,0)};else{var h=new t.MessageChannel;h.port1.onmessage=m,r=function(){h.port2.postMessage(0)}}var u=[];function m(){var p,g;o=!0;for(var f=u.length;f;){for(g=u,u=[],p=-1;++p<f;)g[p]();f=u.length}o=!1}i.exports=function(p){u.push(p)!==1||o||r()}}).call(this,typeof global!="undefined"?global:typeof self!="undefined"?self:typeof window!="undefined"?window:{})},{}],37:[function(s,i,e){"use strict";var t=s("immediate");function r(){}var o={},n=["REJECTED"],a=["FULFILLED"],d=["PENDING"];function l(f){if(typeof f!="function")throw new TypeError("resolver must be a function");this.state=d,this.queue=[],this.outcome=void 0,f!==r&&p(this,f)}function h(f,T,I){this.promise=f,typeof T=="function"&&(this.onFulfilled=T,this.callFulfilled=this.otherCallFulfilled),typeof I=="function"&&(this.onRejected=I,this.callRejected=this.otherCallRejected)}function u(f,T,I){t(function(){var v;try{v=T(I)}catch(b){return o.reject(f,b)}v===f?o.reject(f,new TypeError("Cannot resolve promise with itself")):o.resolve(f,v)})}function m(f){var T=f&&f.then;if(f&&(typeof f=="object"||typeof f=="function")&&typeof T=="function")return function(){T.apply(f,arguments)}}function p(f,T){var I=!1;function v(N){I||(I=!0,o.reject(f,N))}function b(N){I||(I=!0,o.resolve(f,N))}var w=g(function(){T(b,v)});w.status==="error"&&v(w.value)}function g(f,T){var I={};try{I.value=f(T),I.status="success"}catch(v){I.status="error",I.value=v}return I}(i.exports=l).prototype.finally=function(f){if(typeof f!="function")return this;var T=this.constructor;return this.then(function(I){return T.resolve(f()).then(function(){return I})},function(I){return T.resolve(f()).then(function(){throw I})})},l.prototype.catch=function(f){return this.then(null,f)},l.prototype.then=function(f,T){if(typeof f!="function"&&this.state===a||typeof T!="function"&&this.state===n)return this;var I=new this.constructor(r);return this.state!==d?u(I,this.state===a?f:T,this.outcome):this.queue.push(new h(I,f,T)),I},h.prototype.callFulfilled=function(f){o.resolve(this.promise,f)},h.prototype.otherCallFulfilled=function(f){u(this.promise,this.onFulfilled,f)},h.prototype.callRejected=function(f){o.reject(this.promise,f)},h.prototype.otherCallRejected=function(f){u(this.promise,this.onRejected,f)},o.resolve=function(f,T){var I=g(m,T);if(I.status==="error")return o.reject(f,I.value);var v=I.value;if(v)p(f,v);else{f.state=a,f.outcome=T;for(var b=-1,w=f.queue.length;++b<w;)f.queue[b].callFulfilled(T)}return f},o.reject=function(f,T){f.state=n,f.outcome=T;for(var I=-1,v=f.queue.length;++I<v;)f.queue[I].callRejected(T);return f},l.resolve=function(f){return f instanceof this?f:o.resolve(new this(r),f)},l.reject=function(f){var T=new this(r);return o.reject(T,f)},l.all=function(f){var T=this;if(Object.prototype.toString.call(f)!=="[object Array]")return this.reject(new TypeError("must be an array"));var I=f.length,v=!1;if(!I)return this.resolve([]);for(var b=new Array(I),w=0,N=-1,q=new this(r);++N<I;)$(f[N],N);return q;function $(te,se){T.resolve(te).then(function(y){b[se]=y,++w!==I||v||(v=!0,o.resolve(q,b))},function(y){v||(v=!0,o.reject(q,y))})}},l.race=function(f){var T=this;if(Object.prototype.toString.call(f)!=="[object Array]")return this.reject(new TypeError("must be an array"));var I=f.length,v=!1;if(!I)return this.resolve([]);for(var b=-1,w=new this(r);++b<I;)N=f[b],T.resolve(N).then(function(q){v||(v=!0,o.resolve(w,q))},function(q){v||(v=!0,o.reject(w,q))});var N;return w}},{immediate:36}],38:[function(s,i,e){"use strict";var t={};(0,s("./lib/utils/common").assign)(t,s("./lib/deflate"),s("./lib/inflate"),s("./lib/zlib/constants")),i.exports=t},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(s,i,e){"use strict";var t=s("./zlib/deflate"),r=s("./utils/common"),o=s("./utils/strings"),n=s("./zlib/messages"),a=s("./zlib/zstream"),d=Object.prototype.toString,l=0,h=-1,u=0,m=8;function p(f){if(!(this instanceof p))return new p(f);this.options=r.assign({level:h,method:m,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},f||{});var T=this.options;T.raw&&0<T.windowBits?T.windowBits=-T.windowBits:T.gzip&&0<T.windowBits&&T.windowBits<16&&(T.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var I=t.deflateInit2(this.strm,T.level,T.method,T.windowBits,T.memLevel,T.strategy);if(I!==l)throw new Error(n[I]);if(T.header&&t.deflateSetHeader(this.strm,T.header),T.dictionary){var v;if(v=typeof T.dictionary=="string"?o.string2buf(T.dictionary):d.call(T.dictionary)==="[object ArrayBuffer]"?new Uint8Array(T.dictionary):T.dictionary,(I=t.deflateSetDictionary(this.strm,v))!==l)throw new Error(n[I]);this._dict_set=!0}}function g(f,T){var I=new p(T);if(I.push(f,!0),I.err)throw I.msg||n[I.err];return I.result}p.prototype.push=function(f,T){var I,v,b=this.strm,w=this.options.chunkSize;if(this.ended)return!1;v=T===~~T?T:T===!0?4:0,typeof f=="string"?b.input=o.string2buf(f):d.call(f)==="[object ArrayBuffer]"?b.input=new Uint8Array(f):b.input=f,b.next_in=0,b.avail_in=b.input.length;do{if(b.avail_out===0&&(b.output=new r.Buf8(w),b.next_out=0,b.avail_out=w),(I=t.deflate(b,v))!==1&&I!==l)return this.onEnd(I),!(this.ended=!0);b.avail_out!==0&&(b.avail_in!==0||v!==4&&v!==2)||(this.options.to==="string"?this.onData(o.buf2binstring(r.shrinkBuf(b.output,b.next_out))):this.onData(r.shrinkBuf(b.output,b.next_out)))}while((0<b.avail_in||b.avail_out===0)&&I!==1);return v===4?(I=t.deflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===l):v!==2||(this.onEnd(l),!(b.avail_out=0))},p.prototype.onData=function(f){this.chunks.push(f)},p.prototype.onEnd=function(f){f===l&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=f,this.msg=this.strm.msg},e.Deflate=p,e.deflate=g,e.deflateRaw=function(f,T){return(T=T||{}).raw=!0,g(f,T)},e.gzip=function(f,T){return(T=T||{}).gzip=!0,g(f,T)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(s,i,e){"use strict";var t=s("./zlib/inflate"),r=s("./utils/common"),o=s("./utils/strings"),n=s("./zlib/constants"),a=s("./zlib/messages"),d=s("./zlib/zstream"),l=s("./zlib/gzheader"),h=Object.prototype.toString;function u(p){if(!(this instanceof u))return new u(p);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},p||{});var g=this.options;g.raw&&0<=g.windowBits&&g.windowBits<16&&(g.windowBits=-g.windowBits,g.windowBits===0&&(g.windowBits=-15)),!(0<=g.windowBits&&g.windowBits<16)||p&&p.windowBits||(g.windowBits+=32),15<g.windowBits&&g.windowBits<48&&(15&g.windowBits)==0&&(g.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var f=t.inflateInit2(this.strm,g.windowBits);if(f!==n.Z_OK)throw new Error(a[f]);this.header=new l,t.inflateGetHeader(this.strm,this.header)}function m(p,g){var f=new u(g);if(f.push(p,!0),f.err)throw f.msg||a[f.err];return f.result}u.prototype.push=function(p,g){var f,T,I,v,b,w,N=this.strm,q=this.options.chunkSize,$=this.options.dictionary,te=!1;if(this.ended)return!1;T=g===~~g?g:g===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof p=="string"?N.input=o.binstring2buf(p):h.call(p)==="[object ArrayBuffer]"?N.input=new Uint8Array(p):N.input=p,N.next_in=0,N.avail_in=N.input.length;do{if(N.avail_out===0&&(N.output=new r.Buf8(q),N.next_out=0,N.avail_out=q),(f=t.inflate(N,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&$&&(w=typeof $=="string"?o.string2buf($):h.call($)==="[object ArrayBuffer]"?new Uint8Array($):$,f=t.inflateSetDictionary(this.strm,w)),f===n.Z_BUF_ERROR&&te===!0&&(f=n.Z_OK,te=!1),f!==n.Z_STREAM_END&&f!==n.Z_OK)return this.onEnd(f),!(this.ended=!0);N.next_out&&(N.avail_out!==0&&f!==n.Z_STREAM_END&&(N.avail_in!==0||T!==n.Z_FINISH&&T!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(I=o.utf8border(N.output,N.next_out),v=N.next_out-I,b=o.buf2string(N.output,I),N.next_out=v,N.avail_out=q-v,v&&r.arraySet(N.output,N.output,I,v,0),this.onData(b)):this.onData(r.shrinkBuf(N.output,N.next_out)))),N.avail_in===0&&N.avail_out===0&&(te=!0)}while((0<N.avail_in||N.avail_out===0)&&f!==n.Z_STREAM_END);return f===n.Z_STREAM_END&&(T=n.Z_FINISH),T===n.Z_FINISH?(f=t.inflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===n.Z_OK):T!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(N.avail_out=0))},u.prototype.onData=function(p){this.chunks.push(p)},u.prototype.onEnd=function(p){p===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},e.Inflate=u,e.inflate=m,e.inflateRaw=function(p,g){return(g=g||{}).raw=!0,m(p,g)},e.ungzip=m},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(s,i,e){"use strict";var t=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";e.assign=function(n){for(var a=Array.prototype.slice.call(arguments,1);a.length;){var d=a.shift();if(d){if(typeof d!="object")throw new TypeError(d+"must be non-object");for(var l in d)d.hasOwnProperty(l)&&(n[l]=d[l])}}return n},e.shrinkBuf=function(n,a){return n.length===a?n:n.subarray?n.subarray(0,a):(n.length=a,n)};var r={arraySet:function(n,a,d,l,h){if(a.subarray&&n.subarray)n.set(a.subarray(d,d+l),h);else for(var u=0;u<l;u++)n[h+u]=a[d+u]},flattenChunks:function(n){var a,d,l,h,u,m;for(a=l=0,d=n.length;a<d;a++)l+=n[a].length;for(m=new Uint8Array(l),a=h=0,d=n.length;a<d;a++)u=n[a],m.set(u,h),h+=u.length;return m}},o={arraySet:function(n,a,d,l,h){for(var u=0;u<l;u++)n[h+u]=a[d+u]},flattenChunks:function(n){return[].concat.apply([],n)}};e.setTyped=function(n){n?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,r)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(t)},{}],42:[function(s,i,e){"use strict";var t=s("./common"),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(l){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(l){o=!1}for(var n=new t.Buf8(256),a=0;a<256;a++)n[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function d(l,h){if(h<65537&&(l.subarray&&o||!l.subarray&&r))return String.fromCharCode.apply(null,t.shrinkBuf(l,h));for(var u="",m=0;m<h;m++)u+=String.fromCharCode(l[m]);return u}n[254]=n[254]=1,e.string2buf=function(l){var h,u,m,p,g,f=l.length,T=0;for(p=0;p<f;p++)(64512&(u=l.charCodeAt(p)))==55296&&p+1<f&&(64512&(m=l.charCodeAt(p+1)))==56320&&(u=65536+(u-55296<<10)+(m-56320),p++),T+=u<128?1:u<2048?2:u<65536?3:4;for(h=new t.Buf8(T),p=g=0;g<T;p++)(64512&(u=l.charCodeAt(p)))==55296&&p+1<f&&(64512&(m=l.charCodeAt(p+1)))==56320&&(u=65536+(u-55296<<10)+(m-56320),p++),u<128?h[g++]=u:(u<2048?h[g++]=192|u>>>6:(u<65536?h[g++]=224|u>>>12:(h[g++]=240|u>>>18,h[g++]=128|u>>>12&63),h[g++]=128|u>>>6&63),h[g++]=128|63&u);return h},e.buf2binstring=function(l){return d(l,l.length)},e.binstring2buf=function(l){for(var h=new t.Buf8(l.length),u=0,m=h.length;u<m;u++)h[u]=l.charCodeAt(u);return h},e.buf2string=function(l,h){var u,m,p,g,f=h||l.length,T=new Array(2*f);for(u=m=0;u<f;)if((p=l[u++])<128)T[m++]=p;else if(4<(g=n[p]))T[m++]=65533,u+=g-1;else{for(p&=g===2?31:g===3?15:7;1<g&&u<f;)p=p<<6|63&l[u++],g--;1<g?T[m++]=65533:p<65536?T[m++]=p:(p-=65536,T[m++]=55296|p>>10&1023,T[m++]=56320|1023&p)}return d(T,m)},e.utf8border=function(l,h){var u;for((h=h||l.length)>l.length&&(h=l.length),u=h-1;0<=u&&(192&l[u])==128;)u--;return u<0||u===0?h:u+n[l[u]]>h?u:h}},{"./common":41}],43:[function(s,i,e){"use strict";i.exports=function(t,r,o,n){for(var a=65535&t|0,d=t>>>16&65535|0,l=0;o!==0;){for(o-=l=2e3<o?2e3:o;d=d+(a=a+r[n++]|0)|0,--l;);a%=65521,d%=65521}return a|d<<16|0}},{}],44:[function(s,i,e){"use strict";i.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(s,i,e){"use strict";var t=function(){for(var r,o=[],n=0;n<256;n++){r=n;for(var a=0;a<8;a++)r=1&r?3988292384^r>>>1:r>>>1;o[n]=r}return o}();i.exports=function(r,o,n,a){var d=t,l=a+n;r^=-1;for(var h=a;h<l;h++)r=r>>>8^d[255&(r^o[h])];return-1^r}},{}],46:[function(s,i,e){"use strict";var t,r=s("../utils/common"),o=s("./trees"),n=s("./adler32"),a=s("./crc32"),d=s("./messages"),l=0,h=4,u=0,m=-2,p=-1,g=4,f=2,T=8,I=9,v=286,b=30,w=19,N=2*v+1,q=15,$=3,te=258,se=te+$+1,y=42,G=113,E=1,j=2,Ce=3,O=4;function Ne(_,k){return _.msg=d[k],k}function ee(_){return(_<<1)-(4<_?9:0)}function he(_){for(var k=_.length;0<=--k;)_[k]=0}function V(_){var k=_.state,F=k.pending;F>_.avail_out&&(F=_.avail_out),F!==0&&(r.arraySet(_.output,k.pending_buf,k.pending_out,F,_.next_out),_.next_out+=F,k.pending_out+=F,_.total_out+=F,_.avail_out-=F,k.pending-=F,k.pending===0&&(k.pending_out=0))}function P(_,k){o._tr_flush_block(_,0<=_.block_start?_.block_start:-1,_.strstart-_.block_start,k),_.block_start=_.strstart,V(_.strm)}function _e(_,k){_.pending_buf[_.pending++]=k}function ae(_,k){_.pending_buf[_.pending++]=k>>>8&255,_.pending_buf[_.pending++]=255&k}function oe(_,k){var F,R,C=_.max_chain_length,D=_.strstart,Y=_.prev_length,K=_.nice_match,L=_.strstart>_.w_size-se?_.strstart-(_.w_size-se):0,ie=_.window,ce=_.w_mask,re=_.prev,Se=_.strstart+te,U=ie[D+Y-1],Pe=ie[D+Y];_.prev_length>=_.good_match&&(C>>=2),K>_.lookahead&&(K=_.lookahead);do if(ie[(F=k)+Y]===Pe&&ie[F+Y-1]===U&&ie[F]===ie[D]&&ie[++F]===ie[D+1]){D+=2,F++;do;while(ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&ie[++D]===ie[++F]&&D<Se);if(R=te-(Se-D),D=Se-te,Y<R){if(_.match_start=k,K<=(Y=R))break;U=ie[D+Y-1],Pe=ie[D+Y]}}while((k=re[k&ce])>L&&--C!=0);return Y<=_.lookahead?Y:_.lookahead}function st(_){var k,F,R,C,D,Y,K,L,ie,ce,re=_.w_size;do{if(C=_.window_size-_.lookahead-_.strstart,_.strstart>=re+(re-se)){for(r.arraySet(_.window,_.window,re,re,0),_.match_start-=re,_.strstart-=re,_.block_start-=re,k=F=_.hash_size;R=_.head[--k],_.head[k]=re<=R?R-re:0,--F;);for(k=F=re;R=_.prev[--k],_.prev[k]=re<=R?R-re:0,--F;);C+=re}if(_.strm.avail_in===0)break;if(Y=_.strm,K=_.window,L=_.strstart+_.lookahead,ie=C,ce=void 0,ce=Y.avail_in,ie<ce&&(ce=ie),F=ce===0?0:(Y.avail_in-=ce,r.arraySet(K,Y.input,Y.next_in,ce,L),Y.state.wrap===1?Y.adler=n(Y.adler,K,ce,L):Y.state.wrap===2&&(Y.adler=a(Y.adler,K,ce,L)),Y.next_in+=ce,Y.total_in+=ce,ce),_.lookahead+=F,_.lookahead+_.insert>=$)for(D=_.strstart-_.insert,_.ins_h=_.window[D],_.ins_h=(_.ins_h<<_.hash_shift^_.window[D+1])&_.hash_mask;_.insert&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[D+$-1])&_.hash_mask,_.prev[D&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=D,D++,_.insert--,!(_.lookahead+_.insert<$)););}while(_.lookahead<se&&_.strm.avail_in!==0)}function yt(_,k){for(var F,R;;){if(_.lookahead<se){if(st(_),_.lookahead<se&&k===l)return E;if(_.lookahead===0)break}if(F=0,_.lookahead>=$&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+$-1])&_.hash_mask,F=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart),F!==0&&_.strstart-F<=_.w_size-se&&(_.match_length=oe(_,F)),_.match_length>=$)if(R=o._tr_tally(_,_.strstart-_.match_start,_.match_length-$),_.lookahead-=_.match_length,_.match_length<=_.max_lazy_match&&_.lookahead>=$){for(_.match_length--;_.strstart++,_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+$-1])&_.hash_mask,F=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart,--_.match_length!=0;);_.strstart++}else _.strstart+=_.match_length,_.match_length=0,_.ins_h=_.window[_.strstart],_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+1])&_.hash_mask;else R=o._tr_tally(_,0,_.window[_.strstart]),_.lookahead--,_.strstart++;if(R&&(P(_,!1),_.strm.avail_out===0))return E}return _.insert=_.strstart<$-1?_.strstart:$-1,k===h?(P(_,!0),_.strm.avail_out===0?Ce:O):_.last_lit&&(P(_,!1),_.strm.avail_out===0)?E:j}function W(_,k){for(var F,R,C;;){if(_.lookahead<se){if(st(_),_.lookahead<se&&k===l)return E;if(_.lookahead===0)break}if(F=0,_.lookahead>=$&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+$-1])&_.hash_mask,F=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart),_.prev_length=_.match_length,_.prev_match=_.match_start,_.match_length=$-1,F!==0&&_.prev_length<_.max_lazy_match&&_.strstart-F<=_.w_size-se&&(_.match_length=oe(_,F),_.match_length<=5&&(_.strategy===1||_.match_length===$&&4096<_.strstart-_.match_start)&&(_.match_length=$-1)),_.prev_length>=$&&_.match_length<=_.prev_length){for(C=_.strstart+_.lookahead-$,R=o._tr_tally(_,_.strstart-1-_.prev_match,_.prev_length-$),_.lookahead-=_.prev_length-1,_.prev_length-=2;++_.strstart<=C&&(_.ins_h=(_.ins_h<<_.hash_shift^_.window[_.strstart+$-1])&_.hash_mask,F=_.prev[_.strstart&_.w_mask]=_.head[_.ins_h],_.head[_.ins_h]=_.strstart),--_.prev_length!=0;);if(_.match_available=0,_.match_length=$-1,_.strstart++,R&&(P(_,!1),_.strm.avail_out===0))return E}else if(_.match_available){if((R=o._tr_tally(_,0,_.window[_.strstart-1]))&&P(_,!1),_.strstart++,_.lookahead--,_.strm.avail_out===0)return E}else _.match_available=1,_.strstart++,_.lookahead--}return _.match_available&&(R=o._tr_tally(_,0,_.window[_.strstart-1]),_.match_available=0),_.insert=_.strstart<$-1?_.strstart:$-1,k===h?(P(_,!0),_.strm.avail_out===0?Ce:O):_.last_lit&&(P(_,!1),_.strm.avail_out===0)?E:j}function Be(_,k,F,R,C){this.good_length=_,this.max_lazy=k,this.nice_length=F,this.max_chain=R,this.func=C}function _t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=T,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*N),this.dyn_dtree=new r.Buf16(2*(2*b+1)),this.bl_tree=new r.Buf16(2*(2*w+1)),he(this.dyn_ltree),he(this.dyn_dtree),he(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(q+1),this.heap=new r.Buf16(2*v+1),he(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*v+1),he(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function ot(_){var k;return _&&_.state?(_.total_in=_.total_out=0,_.data_type=f,(k=_.state).pending=0,k.pending_out=0,k.wrap<0&&(k.wrap=-k.wrap),k.status=k.wrap?y:G,_.adler=k.wrap===2?0:1,k.last_flush=l,o._tr_init(k),u):Ne(_,m)}function Di(_){var k=ot(_);return k===u&&function(F){F.window_size=2*F.w_size,he(F.head),F.max_lazy_match=t[F.level].max_lazy,F.good_match=t[F.level].good_length,F.nice_match=t[F.level].nice_length,F.max_chain_length=t[F.level].max_chain,F.strstart=0,F.block_start=0,F.lookahead=0,F.insert=0,F.match_length=F.prev_length=$-1,F.match_available=0,F.ins_h=0}(_.state),k}function ui(_,k,F,R,C,D){if(!_)return m;var Y=1;if(k===p&&(k=6),R<0?(Y=0,R=-R):15<R&&(Y=2,R-=16),C<1||I<C||F!==T||R<8||15<R||k<0||9<k||D<0||g<D)return Ne(_,m);R===8&&(R=9);var K=new _t;return(_.state=K).strm=_,K.wrap=Y,K.gzhead=null,K.w_bits=R,K.w_size=1<<K.w_bits,K.w_mask=K.w_size-1,K.hash_bits=C+7,K.hash_size=1<<K.hash_bits,K.hash_mask=K.hash_size-1,K.hash_shift=~~((K.hash_bits+$-1)/$),K.window=new r.Buf8(2*K.w_size),K.head=new r.Buf16(K.hash_size),K.prev=new r.Buf16(K.w_size),K.lit_bufsize=1<<C+6,K.pending_buf_size=4*K.lit_bufsize,K.pending_buf=new r.Buf8(K.pending_buf_size),K.d_buf=1*K.lit_bufsize,K.l_buf=3*K.lit_bufsize,K.level=k,K.strategy=D,K.method=F,Di(_)}t=[new Be(0,0,0,0,function(_,k){var F=65535;for(F>_.pending_buf_size-5&&(F=_.pending_buf_size-5);;){if(_.lookahead<=1){if(st(_),_.lookahead===0&&k===l)return E;if(_.lookahead===0)break}_.strstart+=_.lookahead,_.lookahead=0;var R=_.block_start+F;if((_.strstart===0||_.strstart>=R)&&(_.lookahead=_.strstart-R,_.strstart=R,P(_,!1),_.strm.avail_out===0)||_.strstart-_.block_start>=_.w_size-se&&(P(_,!1),_.strm.avail_out===0))return E}return _.insert=0,k===h?(P(_,!0),_.strm.avail_out===0?Ce:O):(_.strstart>_.block_start&&(P(_,!1),_.strm.avail_out),E)}),new Be(4,4,8,4,yt),new Be(4,5,16,8,yt),new Be(4,6,32,32,yt),new Be(4,4,16,16,W),new Be(8,16,32,32,W),new Be(8,16,128,128,W),new Be(8,32,128,256,W),new Be(32,128,258,1024,W),new Be(32,258,258,4096,W)],e.deflateInit=function(_,k){return ui(_,k,T,15,8,0)},e.deflateInit2=ui,e.deflateReset=Di,e.deflateResetKeep=ot,e.deflateSetHeader=function(_,k){return _&&_.state?_.state.wrap!==2?m:(_.state.gzhead=k,u):m},e.deflate=function(_,k){var F,R,C,D;if(!_||!_.state||5<k||k<0)return _?Ne(_,m):m;if(R=_.state,!_.output||!_.input&&_.avail_in!==0||R.status===666&&k!==h)return Ne(_,_.avail_out===0?-5:m);if(R.strm=_,F=R.last_flush,R.last_flush=k,R.status===y)if(R.wrap===2)_.adler=0,_e(R,31),_e(R,139),_e(R,8),R.gzhead?(_e(R,(R.gzhead.text?1:0)+(R.gzhead.hcrc?2:0)+(R.gzhead.extra?4:0)+(R.gzhead.name?8:0)+(R.gzhead.comment?16:0)),_e(R,255&R.gzhead.time),_e(R,R.gzhead.time>>8&255),_e(R,R.gzhead.time>>16&255),_e(R,R.gzhead.time>>24&255),_e(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),_e(R,255&R.gzhead.os),R.gzhead.extra&&R.gzhead.extra.length&&(_e(R,255&R.gzhead.extra.length),_e(R,R.gzhead.extra.length>>8&255)),R.gzhead.hcrc&&(_.adler=a(_.adler,R.pending_buf,R.pending,0)),R.gzindex=0,R.status=69):(_e(R,0),_e(R,0),_e(R,0),_e(R,0),_e(R,0),_e(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),_e(R,3),R.status=G);else{var Y=T+(R.w_bits-8<<4)<<8;Y|=(2<=R.strategy||R.level<2?0:R.level<6?1:R.level===6?2:3)<<6,R.strstart!==0&&(Y|=32),Y+=31-Y%31,R.status=G,ae(R,Y),R.strstart!==0&&(ae(R,_.adler>>>16),ae(R,65535&_.adler)),_.adler=1}if(R.status===69)if(R.gzhead.extra){for(C=R.pending;R.gzindex<(65535&R.gzhead.extra.length)&&(R.pending!==R.pending_buf_size||(R.gzhead.hcrc&&R.pending>C&&(_.adler=a(_.adler,R.pending_buf,R.pending-C,C)),V(_),C=R.pending,R.pending!==R.pending_buf_size));)_e(R,255&R.gzhead.extra[R.gzindex]),R.gzindex++;R.gzhead.hcrc&&R.pending>C&&(_.adler=a(_.adler,R.pending_buf,R.pending-C,C)),R.gzindex===R.gzhead.extra.length&&(R.gzindex=0,R.status=73)}else R.status=73;if(R.status===73)if(R.gzhead.name){C=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>C&&(_.adler=a(_.adler,R.pending_buf,R.pending-C,C)),V(_),C=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindex<R.gzhead.name.length?255&R.gzhead.name.charCodeAt(R.gzindex++):0,_e(R,D)}while(D!==0);R.gzhead.hcrc&&R.pending>C&&(_.adler=a(_.adler,R.pending_buf,R.pending-C,C)),D===0&&(R.gzindex=0,R.status=91)}else R.status=91;if(R.status===91)if(R.gzhead.comment){C=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>C&&(_.adler=a(_.adler,R.pending_buf,R.pending-C,C)),V(_),C=R.pending,R.pending===R.pending_buf_size)){D=1;break}D=R.gzindex<R.gzhead.comment.length?255&R.gzhead.comment.charCodeAt(R.gzindex++):0,_e(R,D)}while(D!==0);R.gzhead.hcrc&&R.pending>C&&(_.adler=a(_.adler,R.pending_buf,R.pending-C,C)),D===0&&(R.status=103)}else R.status=103;if(R.status===103&&(R.gzhead.hcrc?(R.pending+2>R.pending_buf_size&&V(_),R.pending+2<=R.pending_buf_size&&(_e(R,255&_.adler),_e(R,_.adler>>8&255),_.adler=0,R.status=G)):R.status=G),R.pending!==0){if(V(_),_.avail_out===0)return R.last_flush=-1,u}else if(_.avail_in===0&&ee(k)<=ee(F)&&k!==h)return Ne(_,-5);if(R.status===666&&_.avail_in!==0)return Ne(_,-5);if(_.avail_in!==0||R.lookahead!==0||k!==l&&R.status!==666){var K=R.strategy===2?function(L,ie){for(var ce;;){if(L.lookahead===0&&(st(L),L.lookahead===0)){if(ie===l)return E;break}if(L.match_length=0,ce=o._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++,ce&&(P(L,!1),L.strm.avail_out===0))return E}return L.insert=0,ie===h?(P(L,!0),L.strm.avail_out===0?Ce:O):L.last_lit&&(P(L,!1),L.strm.avail_out===0)?E:j}(R,k):R.strategy===3?function(L,ie){for(var ce,re,Se,U,Pe=L.window;;){if(L.lookahead<=te){if(st(L),L.lookahead<=te&&ie===l)return E;if(L.lookahead===0)break}if(L.match_length=0,L.lookahead>=$&&0<L.strstart&&(re=Pe[Se=L.strstart-1])===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]){U=L.strstart+te;do;while(re===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]&&re===Pe[++Se]&&Se<U);L.match_length=te-(U-Se),L.match_length>L.lookahead&&(L.match_length=L.lookahead)}if(L.match_length>=$?(ce=o._tr_tally(L,1,L.match_length-$),L.lookahead-=L.match_length,L.strstart+=L.match_length,L.match_length=0):(ce=o._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++),ce&&(P(L,!1),L.strm.avail_out===0))return E}return L.insert=0,ie===h?(P(L,!0),L.strm.avail_out===0?Ce:O):L.last_lit&&(P(L,!1),L.strm.avail_out===0)?E:j}(R,k):t[R.level].func(R,k);if(K!==Ce&&K!==O||(R.status=666),K===E||K===Ce)return _.avail_out===0&&(R.last_flush=-1),u;if(K===j&&(k===1?o._tr_align(R):k!==5&&(o._tr_stored_block(R,0,0,!1),k===3&&(he(R.head),R.lookahead===0&&(R.strstart=0,R.block_start=0,R.insert=0))),V(_),_.avail_out===0))return R.last_flush=-1,u}return k!==h?u:R.wrap<=0?1:(R.wrap===2?(_e(R,255&_.adler),_e(R,_.adler>>8&255),_e(R,_.adler>>16&255),_e(R,_.adler>>24&255),_e(R,255&_.total_in),_e(R,_.total_in>>8&255),_e(R,_.total_in>>16&255),_e(R,_.total_in>>24&255)):(ae(R,_.adler>>>16),ae(R,65535&_.adler)),V(_),0<R.wrap&&(R.wrap=-R.wrap),R.pending!==0?u:1)},e.deflateEnd=function(_){var k;return _&&_.state?(k=_.state.status)!==y&&k!==69&&k!==73&&k!==91&&k!==103&&k!==G&&k!==666?Ne(_,m):(_.state=null,k===G?Ne(_,-3):u):m},e.deflateSetDictionary=function(_,k){var F,R,C,D,Y,K,L,ie,ce=k.length;if(!_||!_.state||(D=(F=_.state).wrap)===2||D===1&&F.status!==y||F.lookahead)return m;for(D===1&&(_.adler=n(_.adler,k,ce,0)),F.wrap=0,ce>=F.w_size&&(D===0&&(he(F.head),F.strstart=0,F.block_start=0,F.insert=0),ie=new r.Buf8(F.w_size),r.arraySet(ie,k,ce-F.w_size,F.w_size,0),k=ie,ce=F.w_size),Y=_.avail_in,K=_.next_in,L=_.input,_.avail_in=ce,_.next_in=0,_.input=k,st(F);F.lookahead>=$;){for(R=F.strstart,C=F.lookahead-($-1);F.ins_h=(F.ins_h<<F.hash_shift^F.window[R+$-1])&F.hash_mask,F.prev[R&F.w_mask]=F.head[F.ins_h],F.head[F.ins_h]=R,R++,--C;);F.strstart=R,F.lookahead=$-1,st(F)}return F.strstart+=F.lookahead,F.block_start=F.strstart,F.insert=F.lookahead,F.lookahead=0,F.match_length=F.prev_length=$-1,F.match_available=0,_.next_in=K,_.input=L,_.avail_in=Y,F.wrap=D,u},e.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(s,i,e){"use strict";i.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(s,i,e){"use strict";i.exports=function(t,r){var o,n,a,d,l,h,u,m,p,g,f,T,I,v,b,w,N,q,$,te,se,y,G,E,j;o=t.state,n=t.next_in,E=t.input,a=n+(t.avail_in-5),d=t.next_out,j=t.output,l=d-(r-t.avail_out),h=d+(t.avail_out-257),u=o.dmax,m=o.wsize,p=o.whave,g=o.wnext,f=o.window,T=o.hold,I=o.bits,v=o.lencode,b=o.distcode,w=(1<<o.lenbits)-1,N=(1<<o.distbits)-1;e:do{I<15&&(T+=E[n++]<<I,I+=8,T+=E[n++]<<I,I+=8),q=v[T&w];t:for(;;){if(T>>>=$=q>>>24,I-=$,($=q>>>16&255)===0)j[d++]=65535&q;else{if(!(16&$)){if((64&$)==0){q=v[(65535&q)+(T&(1<<$)-1)];continue t}if(32&$){o.mode=12;break e}t.msg="invalid literal/length code",o.mode=30;break e}te=65535&q,($&=15)&&(I<$&&(T+=E[n++]<<I,I+=8),te+=T&(1<<$)-1,T>>>=$,I-=$),I<15&&(T+=E[n++]<<I,I+=8,T+=E[n++]<<I,I+=8),q=b[T&N];i:for(;;){if(T>>>=$=q>>>24,I-=$,!(16&($=q>>>16&255))){if((64&$)==0){q=b[(65535&q)+(T&(1<<$)-1)];continue i}t.msg="invalid distance code",o.mode=30;break e}if(se=65535&q,I<($&=15)&&(T+=E[n++]<<I,(I+=8)<$&&(T+=E[n++]<<I,I+=8)),u<(se+=T&(1<<$)-1)){t.msg="invalid distance too far back",o.mode=30;break e}if(T>>>=$,I-=$,($=d-l)<se){if(p<($=se-$)&&o.sane){t.msg="invalid distance too far back",o.mode=30;break e}if(G=f,(y=0)===g){if(y+=m-$,$<te){for(te-=$;j[d++]=f[y++],--$;);y=d-se,G=j}}else if(g<$){if(y+=m+g-$,($-=g)<te){for(te-=$;j[d++]=f[y++],--$;);if(y=0,g<te){for(te-=$=g;j[d++]=f[y++],--$;);y=d-se,G=j}}}else if(y+=g-$,$<te){for(te-=$;j[d++]=f[y++],--$;);y=d-se,G=j}for(;2<te;)j[d++]=G[y++],j[d++]=G[y++],j[d++]=G[y++],te-=3;te&&(j[d++]=G[y++],1<te&&(j[d++]=G[y++]))}else{for(y=d-se;j[d++]=j[y++],j[d++]=j[y++],j[d++]=j[y++],2<(te-=3););te&&(j[d++]=j[y++],1<te&&(j[d++]=j[y++]))}break}}break}}while(n<a&&d<h);n-=te=I>>3,T&=(1<<(I-=te<<3))-1,t.next_in=n,t.next_out=d,t.avail_in=n<a?a-n+5:5-(n-a),t.avail_out=d<h?h-d+257:257-(d-h),o.hold=T,o.bits=I}},{}],49:[function(s,i,e){"use strict";var t=s("../utils/common"),r=s("./adler32"),o=s("./crc32"),n=s("./inffast"),a=s("./inftrees"),d=1,l=2,h=0,u=-2,m=1,p=852,g=592;function f(y){return(y>>>24&255)+(y>>>8&65280)+((65280&y)<<8)+((255&y)<<24)}function T(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function I(y){var G;return y&&y.state?(G=y.state,y.total_in=y.total_out=G.total=0,y.msg="",G.wrap&&(y.adler=1&G.wrap),G.mode=m,G.last=0,G.havedict=0,G.dmax=32768,G.head=null,G.hold=0,G.bits=0,G.lencode=G.lendyn=new t.Buf32(p),G.distcode=G.distdyn=new t.Buf32(g),G.sane=1,G.back=-1,h):u}function v(y){var G;return y&&y.state?((G=y.state).wsize=0,G.whave=0,G.wnext=0,I(y)):u}function b(y,G){var E,j;return y&&y.state?(j=y.state,G<0?(E=0,G=-G):(E=1+(G>>4),G<48&&(G&=15)),G&&(G<8||15<G)?u:(j.window!==null&&j.wbits!==G&&(j.window=null),j.wrap=E,j.wbits=G,v(y))):u}function w(y,G){var E,j;return y?(j=new T,(y.state=j).window=null,(E=b(y,G))!==h&&(y.state=null),E):u}var N,q,$=!0;function te(y){if($){var G;for(N=new t.Buf32(512),q=new t.Buf32(32),G=0;G<144;)y.lens[G++]=8;for(;G<256;)y.lens[G++]=9;for(;G<280;)y.lens[G++]=7;for(;G<288;)y.lens[G++]=8;for(a(d,y.lens,0,288,N,0,y.work,{bits:9}),G=0;G<32;)y.lens[G++]=5;a(l,y.lens,0,32,q,0,y.work,{bits:5}),$=!1}y.lencode=N,y.lenbits=9,y.distcode=q,y.distbits=5}function se(y,G,E,j){var Ce,O=y.state;return O.window===null&&(O.wsize=1<<O.wbits,O.wnext=0,O.whave=0,O.window=new t.Buf8(O.wsize)),j>=O.wsize?(t.arraySet(O.window,G,E-O.wsize,O.wsize,0),O.wnext=0,O.whave=O.wsize):(j<(Ce=O.wsize-O.wnext)&&(Ce=j),t.arraySet(O.window,G,E-j,Ce,O.wnext),(j-=Ce)?(t.arraySet(O.window,G,E-j,j,0),O.wnext=j,O.whave=O.wsize):(O.wnext+=Ce,O.wnext===O.wsize&&(O.wnext=0),O.whave<O.wsize&&(O.whave+=Ce))),0}e.inflateReset=v,e.inflateReset2=b,e.inflateResetKeep=I,e.inflateInit=function(y){return w(y,15)},e.inflateInit2=w,e.inflate=function(y,G){var E,j,Ce,O,Ne,ee,he,V,P,_e,ae,oe,st,yt,W,Be,_t,ot,Di,ui,_,k,F,R,C=0,D=new t.Buf8(4),Y=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!y||!y.state||!y.output||!y.input&&y.avail_in!==0)return u;(E=y.state).mode===12&&(E.mode=13),Ne=y.next_out,Ce=y.output,he=y.avail_out,O=y.next_in,j=y.input,ee=y.avail_in,V=E.hold,P=E.bits,_e=ee,ae=he,k=h;e:for(;;)switch(E.mode){case m:if(E.wrap===0){E.mode=13;break}for(;P<16;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(2&E.wrap&&V===35615){D[E.check=0]=255&V,D[1]=V>>>8&255,E.check=o(E.check,D,2,0),P=V=0,E.mode=2;break}if(E.flags=0,E.head&&(E.head.done=!1),!(1&E.wrap)||(((255&V)<<8)+(V>>8))%31){y.msg="incorrect header check",E.mode=30;break}if((15&V)!=8){y.msg="unknown compression method",E.mode=30;break}if(P-=4,_=8+(15&(V>>>=4)),E.wbits===0)E.wbits=_;else if(_>E.wbits){y.msg="invalid window size",E.mode=30;break}E.dmax=1<<_,y.adler=E.check=1,E.mode=512&V?10:12,P=V=0;break;case 2:for(;P<16;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(E.flags=V,(255&E.flags)!=8){y.msg="unknown compression method",E.mode=30;break}if(57344&E.flags){y.msg="unknown header flags set",E.mode=30;break}E.head&&(E.head.text=V>>8&1),512&E.flags&&(D[0]=255&V,D[1]=V>>>8&255,E.check=o(E.check,D,2,0)),P=V=0,E.mode=3;case 3:for(;P<32;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}E.head&&(E.head.time=V),512&E.flags&&(D[0]=255&V,D[1]=V>>>8&255,D[2]=V>>>16&255,D[3]=V>>>24&255,E.check=o(E.check,D,4,0)),P=V=0,E.mode=4;case 4:for(;P<16;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}E.head&&(E.head.xflags=255&V,E.head.os=V>>8),512&E.flags&&(D[0]=255&V,D[1]=V>>>8&255,E.check=o(E.check,D,2,0)),P=V=0,E.mode=5;case 5:if(1024&E.flags){for(;P<16;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}E.length=V,E.head&&(E.head.extra_len=V),512&E.flags&&(D[0]=255&V,D[1]=V>>>8&255,E.check=o(E.check,D,2,0)),P=V=0}else E.head&&(E.head.extra=null);E.mode=6;case 6:if(1024&E.flags&&(ee<(oe=E.length)&&(oe=ee),oe&&(E.head&&(_=E.head.extra_len-E.length,E.head.extra||(E.head.extra=new Array(E.head.extra_len)),t.arraySet(E.head.extra,j,O,oe,_)),512&E.flags&&(E.check=o(E.check,j,oe,O)),ee-=oe,O+=oe,E.length-=oe),E.length))break e;E.length=0,E.mode=7;case 7:if(2048&E.flags){if(ee===0)break e;for(oe=0;_=j[O+oe++],E.head&&_&&E.length<65536&&(E.head.name+=String.fromCharCode(_)),_&&oe<ee;);if(512&E.flags&&(E.check=o(E.check,j,oe,O)),ee-=oe,O+=oe,_)break e}else E.head&&(E.head.name=null);E.length=0,E.mode=8;case 8:if(4096&E.flags){if(ee===0)break e;for(oe=0;_=j[O+oe++],E.head&&_&&E.length<65536&&(E.head.comment+=String.fromCharCode(_)),_&&oe<ee;);if(512&E.flags&&(E.check=o(E.check,j,oe,O)),ee-=oe,O+=oe,_)break e}else E.head&&(E.head.comment=null);E.mode=9;case 9:if(512&E.flags){for(;P<16;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(V!==(65535&E.check)){y.msg="header crc mismatch",E.mode=30;break}P=V=0}E.head&&(E.head.hcrc=E.flags>>9&1,E.head.done=!0),y.adler=E.check=0,E.mode=12;break;case 10:for(;P<32;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}y.adler=E.check=f(V),P=V=0,E.mode=11;case 11:if(E.havedict===0)return y.next_out=Ne,y.avail_out=he,y.next_in=O,y.avail_in=ee,E.hold=V,E.bits=P,2;y.adler=E.check=1,E.mode=12;case 12:if(G===5||G===6)break e;case 13:if(E.last){V>>>=7&P,P-=7&P,E.mode=27;break}for(;P<3;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}switch(E.last=1&V,P-=1,3&(V>>>=1)){case 0:E.mode=14;break;case 1:if(te(E),E.mode=20,G!==6)break;V>>>=2,P-=2;break e;case 2:E.mode=17;break;case 3:y.msg="invalid block type",E.mode=30}V>>>=2,P-=2;break;case 14:for(V>>>=7&P,P-=7&P;P<32;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if((65535&V)!=(V>>>16^65535)){y.msg="invalid stored block lengths",E.mode=30;break}if(E.length=65535&V,P=V=0,E.mode=15,G===6)break e;case 15:E.mode=16;case 16:if(oe=E.length){if(ee<oe&&(oe=ee),he<oe&&(oe=he),oe===0)break e;t.arraySet(Ce,j,O,oe,Ne),ee-=oe,O+=oe,he-=oe,Ne+=oe,E.length-=oe;break}E.mode=12;break;case 17:for(;P<14;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(E.nlen=257+(31&V),V>>>=5,P-=5,E.ndist=1+(31&V),V>>>=5,P-=5,E.ncode=4+(15&V),V>>>=4,P-=4,286<E.nlen||30<E.ndist){y.msg="too many length or distance symbols",E.mode=30;break}E.have=0,E.mode=18;case 18:for(;E.have<E.ncode;){for(;P<3;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}E.lens[Y[E.have++]]=7&V,V>>>=3,P-=3}for(;E.have<19;)E.lens[Y[E.have++]]=0;if(E.lencode=E.lendyn,E.lenbits=7,F={bits:E.lenbits},k=a(0,E.lens,0,19,E.lencode,0,E.work,F),E.lenbits=F.bits,k){y.msg="invalid code lengths set",E.mode=30;break}E.have=0,E.mode=19;case 19:for(;E.have<E.nlen+E.ndist;){for(;Be=(C=E.lencode[V&(1<<E.lenbits)-1])>>>16&255,_t=65535&C,!((W=C>>>24)<=P);){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(_t<16)V>>>=W,P-=W,E.lens[E.have++]=_t;else{if(_t===16){for(R=W+2;P<R;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(V>>>=W,P-=W,E.have===0){y.msg="invalid bit length repeat",E.mode=30;break}_=E.lens[E.have-1],oe=3+(3&V),V>>>=2,P-=2}else if(_t===17){for(R=W+3;P<R;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}P-=W,_=0,oe=3+(7&(V>>>=W)),V>>>=3,P-=3}else{for(R=W+7;P<R;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}P-=W,_=0,oe=11+(127&(V>>>=W)),V>>>=7,P-=7}if(E.have+oe>E.nlen+E.ndist){y.msg="invalid bit length repeat",E.mode=30;break}for(;oe--;)E.lens[E.have++]=_}}if(E.mode===30)break;if(E.lens[256]===0){y.msg="invalid code -- missing end-of-block",E.mode=30;break}if(E.lenbits=9,F={bits:E.lenbits},k=a(d,E.lens,0,E.nlen,E.lencode,0,E.work,F),E.lenbits=F.bits,k){y.msg="invalid literal/lengths set",E.mode=30;break}if(E.distbits=6,E.distcode=E.distdyn,F={bits:E.distbits},k=a(l,E.lens,E.nlen,E.ndist,E.distcode,0,E.work,F),E.distbits=F.bits,k){y.msg="invalid distances set",E.mode=30;break}if(E.mode=20,G===6)break e;case 20:E.mode=21;case 21:if(6<=ee&&258<=he){y.next_out=Ne,y.avail_out=he,y.next_in=O,y.avail_in=ee,E.hold=V,E.bits=P,n(y,ae),Ne=y.next_out,Ce=y.output,he=y.avail_out,O=y.next_in,j=y.input,ee=y.avail_in,V=E.hold,P=E.bits,E.mode===12&&(E.back=-1);break}for(E.back=0;Be=(C=E.lencode[V&(1<<E.lenbits)-1])>>>16&255,_t=65535&C,!((W=C>>>24)<=P);){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(Be&&(240&Be)==0){for(ot=W,Di=Be,ui=_t;Be=(C=E.lencode[ui+((V&(1<<ot+Di)-1)>>ot)])>>>16&255,_t=65535&C,!(ot+(W=C>>>24)<=P);){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}V>>>=ot,P-=ot,E.back+=ot}if(V>>>=W,P-=W,E.back+=W,E.length=_t,Be===0){E.mode=26;break}if(32&Be){E.back=-1,E.mode=12;break}if(64&Be){y.msg="invalid literal/length code",E.mode=30;break}E.extra=15&Be,E.mode=22;case 22:if(E.extra){for(R=E.extra;P<R;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}E.length+=V&(1<<E.extra)-1,V>>>=E.extra,P-=E.extra,E.back+=E.extra}E.was=E.length,E.mode=23;case 23:for(;Be=(C=E.distcode[V&(1<<E.distbits)-1])>>>16&255,_t=65535&C,!((W=C>>>24)<=P);){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if((240&Be)==0){for(ot=W,Di=Be,ui=_t;Be=(C=E.distcode[ui+((V&(1<<ot+Di)-1)>>ot)])>>>16&255,_t=65535&C,!(ot+(W=C>>>24)<=P);){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}V>>>=ot,P-=ot,E.back+=ot}if(V>>>=W,P-=W,E.back+=W,64&Be){y.msg="invalid distance code",E.mode=30;break}E.offset=_t,E.extra=15&Be,E.mode=24;case 24:if(E.extra){for(R=E.extra;P<R;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}E.offset+=V&(1<<E.extra)-1,V>>>=E.extra,P-=E.extra,E.back+=E.extra}if(E.offset>E.dmax){y.msg="invalid distance too far back",E.mode=30;break}E.mode=25;case 25:if(he===0)break e;if(oe=ae-he,E.offset>oe){if((oe=E.offset-oe)>E.whave&&E.sane){y.msg="invalid distance too far back",E.mode=30;break}st=oe>E.wnext?(oe-=E.wnext,E.wsize-oe):E.wnext-oe,oe>E.length&&(oe=E.length),yt=E.window}else yt=Ce,st=Ne-E.offset,oe=E.length;for(he<oe&&(oe=he),he-=oe,E.length-=oe;Ce[Ne++]=yt[st++],--oe;);E.length===0&&(E.mode=21);break;case 26:if(he===0)break e;Ce[Ne++]=E.length,he--,E.mode=21;break;case 27:if(E.wrap){for(;P<32;){if(ee===0)break e;ee--,V|=j[O++]<<P,P+=8}if(ae-=he,y.total_out+=ae,E.total+=ae,ae&&(y.adler=E.check=E.flags?o(E.check,Ce,ae,Ne-ae):r(E.check,Ce,ae,Ne-ae)),ae=he,(E.flags?V:f(V))!==E.check){y.msg="incorrect data check",E.mode=30;break}P=V=0}E.mode=28;case 28:if(E.wrap&&E.flags){for(;P<32;){if(ee===0)break e;ee--,V+=j[O++]<<P,P+=8}if(V!==(4294967295&E.total)){y.msg="incorrect length check",E.mode=30;break}P=V=0}E.mode=29;case 29:k=1;break e;case 30:k=-3;break e;case 31:return-4;case 32:default:return u}return y.next_out=Ne,y.avail_out=he,y.next_in=O,y.avail_in=ee,E.hold=V,E.bits=P,(E.wsize||ae!==y.avail_out&&E.mode<30&&(E.mode<27||G!==4))&&se(y,y.output,y.next_out,ae-y.avail_out)?(E.mode=31,-4):(_e-=y.avail_in,ae-=y.avail_out,y.total_in+=_e,y.total_out+=ae,E.total+=ae,E.wrap&&ae&&(y.adler=E.check=E.flags?o(E.check,Ce,ae,y.next_out-ae):r(E.check,Ce,ae,y.next_out-ae)),y.data_type=E.bits+(E.last?64:0)+(E.mode===12?128:0)+(E.mode===20||E.mode===15?256:0),(_e==0&&ae===0||G===4)&&k===h&&(k=-5),k)},e.inflateEnd=function(y){if(!y||!y.state)return u;var G=y.state;return G.window&&(G.window=null),y.state=null,h},e.inflateGetHeader=function(y,G){var E;return y&&y.state?(2&(E=y.state).wrap)==0?u:((E.head=G).done=!1,h):u},e.inflateSetDictionary=function(y,G){var E,j=G.length;return y&&y.state?(E=y.state).wrap!==0&&E.mode!==11?u:E.mode===11&&r(1,G,j,0)!==E.check?-3:se(y,G,j,j)?(E.mode=31,-4):(E.havedict=1,h):u},e.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(s,i,e){"use strict";var t=s("../utils/common"),r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];i.exports=function(d,l,h,u,m,p,g,f){var T,I,v,b,w,N,q,$,te,se=f.bits,y=0,G=0,E=0,j=0,Ce=0,O=0,Ne=0,ee=0,he=0,V=0,P=null,_e=0,ae=new t.Buf16(16),oe=new t.Buf16(16),st=null,yt=0;for(y=0;y<=15;y++)ae[y]=0;for(G=0;G<u;G++)ae[l[h+G]]++;for(Ce=se,j=15;1<=j&&ae[j]===0;j--);if(j<Ce&&(Ce=j),j===0)return m[p++]=20971520,m[p++]=20971520,f.bits=1,0;for(E=1;E<j&&ae[E]===0;E++);for(Ce<E&&(Ce=E),y=ee=1;y<=15;y++)if(ee<<=1,(ee-=ae[y])<0)return-1;if(0<ee&&(d===0||j!==1))return-1;for(oe[1]=0,y=1;y<15;y++)oe[y+1]=oe[y]+ae[y];for(G=0;G<u;G++)l[h+G]!==0&&(g[oe[l[h+G]]++]=G);if(N=d===0?(P=st=g,19):d===1?(P=r,_e-=257,st=o,yt-=257,256):(P=n,st=a,-1),y=E,w=p,Ne=G=V=0,v=-1,b=(he=1<<(O=Ce))-1,d===1&&852<he||d===2&&592<he)return 1;for(;;){for(q=y-Ne,te=g[G]<N?($=0,g[G]):g[G]>N?($=st[yt+g[G]],P[_e+g[G]]):($=96,0),T=1<<y-Ne,E=I=1<<O;m[w+(V>>Ne)+(I-=T)]=q<<24|$<<16|te|0,I!==0;);for(T=1<<y-1;V&T;)T>>=1;if(T!==0?(V&=T-1,V+=T):V=0,G++,--ae[y]==0){if(y===j)break;y=l[h+g[G]]}if(Ce<y&&(V&b)!==v){for(Ne===0&&(Ne=Ce),w+=E,ee=1<<(O=y-Ne);O+Ne<j&&!((ee-=ae[O+Ne])<=0);)O++,ee<<=1;if(he+=1<<O,d===1&&852<he||d===2&&592<he)return 1;m[v=V&b]=Ce<<24|O<<16|w-p|0}}return V!==0&&(m[w+V]=y-Ne<<24|64<<16|0),f.bits=Ce,0}},{"../utils/common":41}],51:[function(s,i,e){"use strict";i.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(s,i,e){"use strict";var t=s("../utils/common"),r=0,o=1;function n(C){for(var D=C.length;0<=--D;)C[D]=0}var a=0,d=29,l=256,h=l+1+d,u=30,m=19,p=2*h+1,g=15,f=16,T=7,I=256,v=16,b=17,w=18,N=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],q=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],$=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],te=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],se=new Array(2*(h+2));n(se);var y=new Array(2*u);n(y);var G=new Array(512);n(G);var E=new Array(256);n(E);var j=new Array(d);n(j);var Ce,O,Ne,ee=new Array(u);function he(C,D,Y,K,L){this.static_tree=C,this.extra_bits=D,this.extra_base=Y,this.elems=K,this.max_length=L,this.has_stree=C&&C.length}function V(C,D){this.dyn_tree=C,this.max_code=0,this.stat_desc=D}function P(C){return C<256?G[C]:G[256+(C>>>7)]}function _e(C,D){C.pending_buf[C.pending++]=255&D,C.pending_buf[C.pending++]=D>>>8&255}function ae(C,D,Y){C.bi_valid>f-Y?(C.bi_buf|=D<<C.bi_valid&65535,_e(C,C.bi_buf),C.bi_buf=D>>f-C.bi_valid,C.bi_valid+=Y-f):(C.bi_buf|=D<<C.bi_valid&65535,C.bi_valid+=Y)}function oe(C,D,Y){ae(C,Y[2*D],Y[2*D+1])}function st(C,D){for(var Y=0;Y|=1&C,C>>>=1,Y<<=1,0<--D;);return Y>>>1}function yt(C,D,Y){var K,L,ie=new Array(g+1),ce=0;for(K=1;K<=g;K++)ie[K]=ce=ce+Y[K-1]<<1;for(L=0;L<=D;L++){var re=C[2*L+1];re!==0&&(C[2*L]=st(ie[re]++,re))}}function W(C){var D;for(D=0;D<h;D++)C.dyn_ltree[2*D]=0;for(D=0;D<u;D++)C.dyn_dtree[2*D]=0;for(D=0;D<m;D++)C.bl_tree[2*D]=0;C.dyn_ltree[2*I]=1,C.opt_len=C.static_len=0,C.last_lit=C.matches=0}function Be(C){8<C.bi_valid?_e(C,C.bi_buf):0<C.bi_valid&&(C.pending_buf[C.pending++]=C.bi_buf),C.bi_buf=0,C.bi_valid=0}function _t(C,D,Y,K){var L=2*D,ie=2*Y;return C[L]<C[ie]||C[L]===C[ie]&&K[D]<=K[Y]}function ot(C,D,Y){for(var K=C.heap[Y],L=Y<<1;L<=C.heap_len&&(L<C.heap_len&&_t(D,C.heap[L+1],C.heap[L],C.depth)&&L++,!_t(D,K,C.heap[L],C.depth));)C.heap[Y]=C.heap[L],Y=L,L<<=1;C.heap[Y]=K}function Di(C,D,Y){var K,L,ie,ce,re=0;if(C.last_lit!==0)for(;K=C.pending_buf[C.d_buf+2*re]<<8|C.pending_buf[C.d_buf+2*re+1],L=C.pending_buf[C.l_buf+re],re++,K===0?oe(C,L,D):(oe(C,(ie=E[L])+l+1,D),(ce=N[ie])!==0&&ae(C,L-=j[ie],ce),oe(C,ie=P(--K),Y),(ce=q[ie])!==0&&ae(C,K-=ee[ie],ce)),re<C.last_lit;);oe(C,I,D)}function ui(C,D){var Y,K,L,ie=D.dyn_tree,ce=D.stat_desc.static_tree,re=D.stat_desc.has_stree,Se=D.stat_desc.elems,U=-1;for(C.heap_len=0,C.heap_max=p,Y=0;Y<Se;Y++)ie[2*Y]!==0?(C.heap[++C.heap_len]=U=Y,C.depth[Y]=0):ie[2*Y+1]=0;for(;C.heap_len<2;)ie[2*(L=C.heap[++C.heap_len]=U<2?++U:0)]=1,C.depth[L]=0,C.opt_len--,re&&(C.static_len-=ce[2*L+1]);for(D.max_code=U,Y=C.heap_len>>1;1<=Y;Y--)ot(C,ie,Y);for(L=Se;Y=C.heap[1],C.heap[1]=C.heap[C.heap_len--],ot(C,ie,1),K=C.heap[1],C.heap[--C.heap_max]=Y,C.heap[--C.heap_max]=K,ie[2*L]=ie[2*Y]+ie[2*K],C.depth[L]=(C.depth[Y]>=C.depth[K]?C.depth[Y]:C.depth[K])+1,ie[2*Y+1]=ie[2*K+1]=L,C.heap[1]=L++,ot(C,ie,1),2<=C.heap_len;);C.heap[--C.heap_max]=C.heap[1],function(Pe,ii){var zo,ki,jo,nt,Ia,jc,or=ii.dyn_tree,dm=ii.max_code,V_=ii.stat_desc.static_tree,B_=ii.stat_desc.has_stree,$_=ii.stat_desc.extra_bits,cm=ii.stat_desc.extra_base,Jo=ii.stat_desc.max_length,Aa=0;for(nt=0;nt<=g;nt++)Pe.bl_count[nt]=0;for(or[2*Pe.heap[Pe.heap_max]+1]=0,zo=Pe.heap_max+1;zo<p;zo++)Jo<(nt=or[2*or[2*(ki=Pe.heap[zo])+1]+1]+1)&&(nt=Jo,Aa++),or[2*ki+1]=nt,dm<ki||(Pe.bl_count[nt]++,Ia=0,cm<=ki&&(Ia=$_[ki-cm]),jc=or[2*ki],Pe.opt_len+=jc*(nt+Ia),B_&&(Pe.static_len+=jc*(V_[2*ki+1]+Ia)));if(Aa!==0){do{for(nt=Jo-1;Pe.bl_count[nt]===0;)nt--;Pe.bl_count[nt]--,Pe.bl_count[nt+1]+=2,Pe.bl_count[Jo]--,Aa-=2}while(0<Aa);for(nt=Jo;nt!==0;nt--)for(ki=Pe.bl_count[nt];ki!==0;)dm<(jo=Pe.heap[--zo])||(or[2*jo+1]!==nt&&(Pe.opt_len+=(nt-or[2*jo+1])*or[2*jo],or[2*jo+1]=nt),ki--)}}(C,D),yt(ie,U,C.bl_count)}function _(C,D,Y){var K,L,ie=-1,ce=D[1],re=0,Se=7,U=4;for(ce===0&&(Se=138,U=3),D[2*(Y+1)+1]=65535,K=0;K<=Y;K++)L=ce,ce=D[2*(K+1)+1],++re<Se&&L===ce||(re<U?C.bl_tree[2*L]+=re:L!==0?(L!==ie&&C.bl_tree[2*L]++,C.bl_tree[2*v]++):re<=10?C.bl_tree[2*b]++:C.bl_tree[2*w]++,ie=L,U=(re=0)===ce?(Se=138,3):L===ce?(Se=6,3):(Se=7,4))}function k(C,D,Y){var K,L,ie=-1,ce=D[1],re=0,Se=7,U=4;for(ce===0&&(Se=138,U=3),K=0;K<=Y;K++)if(L=ce,ce=D[2*(K+1)+1],!(++re<Se&&L===ce)){if(re<U)for(;oe(C,L,C.bl_tree),--re!=0;);else L!==0?(L!==ie&&(oe(C,L,C.bl_tree),re--),oe(C,v,C.bl_tree),ae(C,re-3,2)):re<=10?(oe(C,b,C.bl_tree),ae(C,re-3,3)):(oe(C,w,C.bl_tree),ae(C,re-11,7));ie=L,U=(re=0)===ce?(Se=138,3):L===ce?(Se=6,3):(Se=7,4)}}n(ee);var F=!1;function R(C,D,Y,K){ae(C,(a<<1)+(K?1:0),3),function(L,ie,ce,re){Be(L),re&&(_e(L,ce),_e(L,~ce)),t.arraySet(L.pending_buf,L.window,ie,ce,L.pending),L.pending+=ce}(C,D,Y,!0)}e._tr_init=function(C){F||(function(){var D,Y,K,L,ie,ce=new Array(g+1);for(L=K=0;L<d-1;L++)for(j[L]=K,D=0;D<1<<N[L];D++)E[K++]=L;for(E[K-1]=L,L=ie=0;L<16;L++)for(ee[L]=ie,D=0;D<1<<q[L];D++)G[ie++]=L;for(ie>>=7;L<u;L++)for(ee[L]=ie<<7,D=0;D<1<<q[L]-7;D++)G[256+ie++]=L;for(Y=0;Y<=g;Y++)ce[Y]=0;for(D=0;D<=143;)se[2*D+1]=8,D++,ce[8]++;for(;D<=255;)se[2*D+1]=9,D++,ce[9]++;for(;D<=279;)se[2*D+1]=7,D++,ce[7]++;for(;D<=287;)se[2*D+1]=8,D++,ce[8]++;for(yt(se,h+1,ce),D=0;D<u;D++)y[2*D+1]=5,y[2*D]=st(D,5);Ce=new he(se,N,l+1,h,g),O=new he(y,q,0,u,g),Ne=new he(new Array(0),$,0,m,T)}(),F=!0),C.l_desc=new V(C.dyn_ltree,Ce),C.d_desc=new V(C.dyn_dtree,O),C.bl_desc=new V(C.bl_tree,Ne),C.bi_buf=0,C.bi_valid=0,W(C)},e._tr_stored_block=R,e._tr_flush_block=function(C,D,Y,K){var L,ie,ce=0;0<C.level?(C.strm.data_type===2&&(C.strm.data_type=function(re){var Se,U=4093624447;for(Se=0;Se<=31;Se++,U>>>=1)if(1&U&&re.dyn_ltree[2*Se]!==0)return r;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return o;for(Se=32;Se<l;Se++)if(re.dyn_ltree[2*Se]!==0)return o;return r}(C)),ui(C,C.l_desc),ui(C,C.d_desc),ce=function(re){var Se;for(_(re,re.dyn_ltree,re.l_desc.max_code),_(re,re.dyn_dtree,re.d_desc.max_code),ui(re,re.bl_desc),Se=m-1;3<=Se&&re.bl_tree[2*te[Se]+1]===0;Se--);return re.opt_len+=3*(Se+1)+5+5+4,Se}(C),L=C.opt_len+3+7>>>3,(ie=C.static_len+3+7>>>3)<=L&&(L=ie)):L=ie=Y+5,Y+4<=L&&D!==-1?R(C,D,Y,K):C.strategy===4||ie===L?(ae(C,2+(K?1:0),3),Di(C,se,y)):(ae(C,4+(K?1:0),3),function(re,Se,U,Pe){var ii;for(ae(re,Se-257,5),ae(re,U-1,5),ae(re,Pe-4,4),ii=0;ii<Pe;ii++)ae(re,re.bl_tree[2*te[ii]+1],3);k(re,re.dyn_ltree,Se-1),k(re,re.dyn_dtree,U-1)}(C,C.l_desc.max_code+1,C.d_desc.max_code+1,ce+1),Di(C,C.dyn_ltree,C.dyn_dtree)),W(C),K&&Be(C)},e._tr_tally=function(C,D,Y){return C.pending_buf[C.d_buf+2*C.last_lit]=D>>>8&255,C.pending_buf[C.d_buf+2*C.last_lit+1]=255&D,C.pending_buf[C.l_buf+C.last_lit]=255&Y,C.last_lit++,D===0?C.dyn_ltree[2*Y]++:(C.matches++,D--,C.dyn_ltree[2*(E[Y]+l+1)]++,C.dyn_dtree[2*P(D)]++),C.last_lit===C.lit_bufsize-1},e._tr_align=function(C){ae(C,2,3),oe(C,I,se),function(D){D.bi_valid===16?(_e(D,D.bi_buf),D.bi_buf=0,D.bi_valid=0):8<=D.bi_valid&&(D.pending_buf[D.pending++]=255&D.bi_buf,D.bi_buf>>=8,D.bi_valid-=8)}(C)}},{"../utils/common":41}],53:[function(s,i,e){"use strict";i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(s,i,e){(function(t){(function(r,o){"use strict";if(!r.setImmediate){var n,a,d,l,h=1,u={},m=!1,p=r.document,g=Object.getPrototypeOf&&Object.getPrototypeOf(r);g=g&&g.setTimeout?g:r,n={}.toString.call(r.process)==="[object process]"?function(v){process.nextTick(function(){T(v)})}:function(){if(r.postMessage&&!r.importScripts){var v=!0,b=r.onmessage;return r.onmessage=function(){v=!1},r.postMessage("","*"),r.onmessage=b,v}}()?(l="setImmediate$"+Math.random()+"$",r.addEventListener?r.addEventListener("message",I,!1):r.attachEvent("onmessage",I),function(v){r.postMessage(l+v,"*")}):r.MessageChannel?((d=new MessageChannel).port1.onmessage=function(v){T(v.data)},function(v){d.port2.postMessage(v)}):p&&"onreadystatechange"in p.createElement("script")?(a=p.documentElement,function(v){var b=p.createElement("script");b.onreadystatechange=function(){T(v),b.onreadystatechange=null,a.removeChild(b),b=null},a.appendChild(b)}):function(v){setTimeout(T,0,v)},g.setImmediate=function(v){typeof v!="function"&&(v=new Function(""+v));for(var b=new Array(arguments.length-1),w=0;w<b.length;w++)b[w]=arguments[w+1];var N={callback:v,args:b};return u[h]=N,n(h),h++},g.clearImmediate=f}function f(v){delete u[v]}function T(v){if(m)setTimeout(T,0,v);else{var b=u[v];if(b){m=!0;try{(function(w){var N=w.callback,q=w.args;switch(q.length){case 0:N();break;case 1:N(q[0]);break;case 2:N(q[0],q[1]);break;case 3:N(q[0],q[1],q[2]);break;default:N.apply(o,q)}})(b)}finally{f(v),m=!1}}}}function I(v){v.source===r&&typeof v.data=="string"&&v.data.indexOf(l)===0&&T(+v.data.slice(l.length))}})(typeof self=="undefined"?t===void 0?this:t:self)}).call(this,typeof global!="undefined"?global:typeof self!="undefined"?self:typeof window!="undefined"?window:{})},{}]},{},[10])(10)})});var zh=Oi((tU,Kf)=>{"use strict";var Zf=Kf.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(Zf).forEach(function(s){var i=Zf[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var i_=Oi(Vr=>{"use strict";var Bo=function(s){return String(Number(s))===s?Number(s):s},CS=function(s,i,e,t){if(t&&!e)i[t]=Bo(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Bo(s[r+1]))},RS=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;CS(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},e_=zh(),yS=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Vr.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(yS).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<(e_[o]||[]).length;a+=1){var d=e_[o][a];if(d.reg.test(n))return RS(d,t,n)}}),i.media=e,i};var t_=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Bo(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Vr.parseParams=function(s){return s.split(/;\s?/).reduce(t_,{})};Vr.parseFmtpConfig=Vr.parseParams;Vr.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Vr.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Bo),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Vr.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(t_,{})})};Vr.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Bo(e):(t=Bo(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var s_=Oi((rU,r_)=>{"use strict";var jh=zh(),bS=/%[sdv%]/g,vS=function(s){var i=1,e=arguments,t=e.length;return s.replace(bS,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""}})},pa=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 vS.apply(null,r)},NS=["v","o","s","i","u","e","p","c","b","t","r","z","a"],DS=["i","c","b","a"];r_.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||NS,t=i.innerOrder||DS,r=[];return e.forEach(function(o){jh[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(pa(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(pa(o,n,a))})})}),s.media.forEach(function(o){r.push(pa("m",jh.m[0],o)),t.forEach(function(n){jh[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(pa(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){r.push(pa(n,a,d))})})})}),r.join(`\r
4
5
  `)+`\r
5
- `}});var Iu=pi(Hi=>{"use strict";var Hr=gp(),XT=Ep();Hi.write=XT;Hi.parse=Hr.parse;Hi.parseParams=Hr.parseParams;Hi.parseFmtpConfig=Hr.parseFmtpConfig;Hi.parsePayloads=Hr.parsePayloads;Hi.parseRemoteCandidates=Hr.parseRemoteCandidates;Hi.parseImageAttributes=Hr.parseImageAttributes;Hi.parseSimulcastStreamList=Hr.parseSimulcastStreamList});import o$ from"webrtc-adapter";var op=Be(Qe());var Hu=(V=>(V[V.INVALID_PARAMETER=4096]="INVALID_PARAMETER",V[V.INVALID_OPERATION=4097]="INVALID_OPERATION",V[V.NOT_SUPPORTED=4098]="NOT_SUPPORTED",V[V.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",V[V.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",V[V.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",V[V.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",V[V.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",V[V.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",V[V.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",V[V.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",V[V.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",V[V.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",V[V.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",V[V.CLIENT_BANNED=16448]="CLIENT_BANNED",V[V.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",V[V.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",V[V.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",V[V.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",V[V.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",V[V.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",V[V.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",V[V.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",V[V.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",V[V.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",V[V.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",V[V.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",V[V.API_CALL_ABORTED=16461]="API_CALL_ABORTED",V[V.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",V[V.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",V[V.UNKNOWN=65535]="UNKNOWN",V))(Hu||{}),S=Hu;var _f=function(s){for(let i in S)if(S[i]===s)return i;return"UNKNOWN"},Oc=class extends Error{constructor({name:e="RtcError",message:t,code:r=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${_f(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},y=Oc;var Gu=new Date().getTime(),kc=0,Wu=function(s){Gu=s,kc=Gu-new Date().getTime();let i=new Date;i.setTime(s),C.info(`baseTime from server: ${i} offset: ${kc}`)},qs=function(){return new Date().getTime()+kc},_n=function(){let s=new Date;return s.setTime(qs()),s.toLocaleString()},gn=function(s){let i=String(s.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${s.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var ct={};fi(ct,{bytes2ms:()=>Zu,calculateScaleResolutionDownNumber:()=>rs,convertObjectNumberToInt:()=>oo,copyProperties:()=>Yu,deepClone:()=>_r,deepMerge:()=>Wt,delay:()=>Ii,fibonacci:()=>Tr,formatedTime:()=>nm,getConstructorName:()=>Zr,getContainerFromElement:()=>om,getEnv:()=>zu,getInternalVersion:()=>rm,getLoggerUrl:()=>Ei,getMediaStreamTrackInfo:()=>Ln,getMuteStateFromFlag:()=>Si,getNetworkType:()=>jc,getNumNetworkType:()=>gr,getReconnectionTimeout:()=>Nt,getStringByteLength:()=>so,getTurnServer:()=>sm,getUint32Version:()=>On,getValueType:()=>Se,getViewListFromView:()=>ts,glog:()=>zc,ipv4ToUint32:()=>es,isArray:()=>Te,isAudioWorkletSupported:()=>im,isBoolean:()=>he,isConstructor:()=>Er,isEmpty:()=>Kr,isFunction:()=>ne,isLangChinese:()=>vt,isMediaStreamTrack:()=>em,isNumber:()=>J,isObject:()=>bt,isOverseaSdkAppId:()=>ro,isPlainObject:()=>He,isPortrait:()=>Qc,isPromise:()=>Qi,isRemoteTrack:()=>tm,isString:()=>K,isUndefined:()=>T,loadImage:()=>is,ms2bytes:()=>Ku,ms2samples:()=>Xc,normalizeUrl:()=>Mn,performanceNow:()=>x,promiseAny:()=>Sr,samples2ms:()=>qc,setNetworkType:()=>Nn,stringify:()=>gt,stringifyIncludeValue:()=>Dn,throttlePromise:()=>kn});var Jc={};fi(Jc,{AUDIO_MUTE_BIT:()=>Rn,AUDIO_STAT_BIT:()=>Xi,AUX_STAT_BIT:()=>mr,AUX_STREAM_MSID:()=>Vc,BACKEND_ENV:()=>Cn,BASE_DOC_URL:()=>Ht,BASE_HOST:()=>Ju,CAPABILITIES_KEYS:()=>vn,CLASS_NAME:()=>Vf,CLOUD_CONSOLE_URL:()=>Sf,CROSS_ROOM_BIT:()=>Uc,DATA_FREEZE_TIMING:()=>bn,DEFAULT_ASSETS_URL:()=>Tn,DOC_URL:()=>If,DTLS_STATE_UNKNOWN:()=>yt,ENV_NAME:()=>_i,EXCHANGE_SDP_TIMEOUT:()=>Gc,IS_WORKER:()=>Xr,IS_WORKLET:()=>zs,KIBANA_EVENT:()=>rt,LOCAL_STREAM_PUBLISH_STATE:()=>qu,LOGGER_CMD_TYPE:()=>Ji,LOGGER_DOMAIN:()=>Lc,LOGGER_DOMAIN_OVERSEA:()=>Pc,LOG_LEVEL:()=>Ct,LOG_LEVEL_NAME:()=>Ff,MAIN_STREAM_MSID:()=>Zs,MAX_RTT:()=>to,MICROPHONE_COMMUNICATIONS:()=>Bf,MICROPHONE_DEFAULT:()=>fr,MUTE_ALL_BIT:()=>Rf,NAME:()=>h,NETWORK_TYPE:()=>En,NOT_SUPPORTED_H264:()=>hr,PAUSED_RETRY_COUNT:()=>pr,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Ks,PEER_CONNECTION_STATE:()=>fe,PEER_LEAVE_REASON:()=>Wc,RECOVER_CAPTURE_INTERVAL:()=>Yr,REMOTE_STREAM_TYPE_AUX:()=>Fc,REMOTE_STREAM_TYPE_MAIN:()=>Bc,RENDER_FREEZE_TIMING:()=>Pf,SCHEDULE_DOMAIN:()=>Ti,SCHEDULE_TIMEOUT:()=>Uf,SDP_SEMANTICS_PLAN_B:()=>zr,SDP_SEMANTICS_UNIFIED_PLAN:()=>zi,SECOND_HOST:()=>Tf,SIGNAL_PING_PONG_INTERVAL:()=>Cf,SIGNAL_PING_TIMEOUT:()=>Af,SIGNAL_RECONNECTION_COUNT:()=>Mf,SMALL_STAT_BIT:()=>Ys,SPEAKER_DEFAULT:()=>eo,STORAGE_EXPIRES_TIME:()=>Sn,STREAM_TYPE_BIG:()=>wf,STREAM_TYPE_SMALL:()=>xf,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Qr,SYNC_USER_LIST_INTERVAL:()=>Lf,Scene:()=>Gt,THIRD_HOST:()=>Ef,TRANSPORT_DIRECTION:()=>ee,TRTC_ERROR_ASSISTANCE:()=>wc,TRTC_QUALITY_BAD:()=>Df,TRTC_QUALITY_DISCONNECTED:()=>kf,TRTC_QUALITY_EXCELLENT:()=>bf,TRTC_QUALITY_GOOD:()=>vf,TRTC_QUALITY_POOR:()=>Nf,TRTC_QUALITY_UNKNOWN:()=>yf,TRTC_QUALITY_VERY_BAD:()=>Of,UPDATE_OFFER_TIMEOUT:()=>Hc,VIDEO_MUTE_BIT:()=>yn,VIDEO_STAT_BIT:()=>qi,audioProfileMap:()=>In,defaultBigVideoProfile:()=>ji,defaultSmallVideoProfile:()=>xc,getRetryCount:()=>gi,getScriptDir:()=>gf,innerVersion:()=>Xs,loggerProxy:()=>Qs,screenProfileMap:()=>An,setLoggerProxy:()=>ur,setRetryCount:()=>$c,setVersion:()=>Mc,version:()=>ke,videoProfileMap:()=>Rt});var Xs="4.15.00.1600",ke="5.0.0";function Mc(s){ke=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));Xs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Xr=typeof importScripts!="undefined",zs=typeof registerProcessor!="undefined",gf=()=>{let s=Xr?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},Qs="",ur=s=>Qs=s,Ju="web.sdk.qcloud.com",Tf="web.sdk.tencent.cn",Ef="web.sdk.cloud.tencent.cn",Sf="https://console.cloud.tencent.com/trtc",Ht=`https://${Ju}/trtc/webrtc/v5/doc`,Tn="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",If=`${Ht}/zh-cn/`,Lc="https://yun.tim.qq.com",Pc="https://apisgp.my-imcloud.com",wc="trtc_error_assistance",Ji={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},_i={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Ct=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(Ct||{}),Af=18e3,Cf=2e3,En={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Sn=7*24*3600*1e3,In={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}},Rt={"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}},ji=Rt["480p_2"],xc=Rt["120p_2"],An={"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",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},ee={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Cn={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Gt=(e=>(e.LIVE="live",e.RTC="rtc",e))(Gt||{}),qi=1,Ys=2,mr=4,Xi=8,Rn=64,yn=16,Rf=112,Uc=128,Zs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Vc="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Bc=h.MAIN,Fc=h.AUXILIARY,yf=0,bf=1,vf=2,Nf=3,Df=4,Of=5,kf=6,yt="unknown",fe={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},ju=1/0;function $c(s){ju=s}function gi(){return ju}var Mf=30,rt={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},Lf=1e4,Hc=1e4,Gc=1e4,zi="unified-plan",zr="plan-b",hr=1028,qu=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(qu||{}),bn=500,Pf=1e3,wf=h.BIG,xf=h.SMALL,Ks=10*1e3,Ti={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Uf=2e3,Vf={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},pr=5,fr="default",eo=fr,Bf="communications",Ff=Object.keys(Ct),Wc=["normal leave","timeout leave","kick","role change"],Qr=10,Yr=2e3,vn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],to=10*1e3;var zu=function(){return new URLSearchParams(location.search).get("trtc_env")||""},ro=s=>Number(s)<14e8,Ei=function(s,i){let e;Qs?e=Qs:e=ro(s)?Pc:Lc;let t=Math.floor(Math.random()*Wi(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},io="unknown";function jc(){if(io!=="unknown")return io;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&&(io=Qu(t,r)),io}function Qu(s,i){if(En[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Nn(s){io=Qu(s)}function gr(){return En[jc()]}function Yu(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 Zu(s,i=48e3){return qc(s/4,i)}function qc(s,i=48e3){return s*1e3/i}function Ku(s,i=48e3){return Xc(s,i)*4}function Xc(s,i=48e3){return s*i/1e3}var zc=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},vt=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},He=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Tr(s,i=1,e=1){return s<=1?e:Tr(s-1,e,i+e)}function Nt(s){return s>8?30*1e3:Tr(s)*1e3}function Se(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ne=s=>typeof s=="function",T=s=>typeof s=="undefined",K=s=>typeof s=="string",J=s=>typeof s=="number",he=s=>typeof s=="boolean",bt=s=>Se(s)==="object",Te=s=>Se(s)==="array",em=s=>Se(s)==="MediaStreamTrack".toLowerCase(),tm=s=>s.isRemote,Qi=s=>Se(s)==="promise",Er=s=>ne(s)&&s.prototype.constructor===s,Zr=s=>Er(s)?s.prototype.constructor.name:"",im=typeof AudioWorkletNode!="undefined";function Sr(s){return new Promise((i,e)=>{let t=[];s.forEach(r=>{r.then(i).catch(o=>{t.push(o),t.length===s.length&&e(t)})})})}function x(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Xu=s=>+s<10?`0${s}`:s,rm=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=Xu(e[1])+Xu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},$f=Object.prototype.hasOwnProperty,{toString:vE}=Object.prototype;function Kr(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(He(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if($f.call(s,i))return!1;return!0}}return!1}function Si(s,i){return{userId:i,hasAudio:!!(s&Xi),hasVideo:!!(s&qi),hasAuxiliary:!!(s&mr),hasSmall:!!(s&Ys),audioMuted:!!(s&Rn),videoMuted:!!(s&yn),audioAvailable:!!(s&Xi)&&!(s&Rn),videoAvailable:!!(s&qi)&&!(s&yn)}}function sm(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!T(s.username)&&!T(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",T(s.credentialType)||(i.credentialType=s.credentialType)),i}function es(s,i=!0){if(!K(s))return 0;let e=s.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Wt=function(s,i,e,t){if(!(bt(s)&&bt(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(T(i[n])||e&&e.includes(n)))if(bt(s[n])&&bt(i[n]))r+=Wt(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=_r(i[n]),r+=1)}return r};function _r(s){if(Te(s)){let i=[];return s.forEach((e,t)=>{i[t]=_r(e)}),i}if(bt(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=_r(s[e])}),i}return s}var ts=s=>{let i=[];if(Te(s))i=[...s];else if(K(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},om=s=>K(s)?document.getElementById(s):s,Hf=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}`},nm=()=>Hf(new Date);function gt(s,{keysToInclude:i,keysToExclude:e}){try{if(Te(s))return`[${s.map(n=>gt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!He(s)||!Te(i)&&!Te(e))return JSON.stringify(s);let t={},r=new Set(i),o=new Set(e);return Object.keys(s).forEach(n=>{(o.size===0&&r.has(n)||r.size===0&&!o.has(n))&&(t[n]=He(s[n])||Te(s[n])?JSON.parse(gt(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Dn(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),gt(s,{keysToInclude:e})}function so(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Qc=()=>{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},is=s=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(K(s))t=new Image,t.crossOrigin="anonymous",t.src=s;else if(t=s,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new y({code:S.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),On=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},oo=s=>(Object.keys(s).forEach(i=>{J(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(He(s[i])||Te(s[i]))&&oo(s[i])}),s);function Ii(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function kn(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function Mn(s){return s.replace(/(^|[^:])\/{2,}/g,"$1/")}function Ln(s){var i;try{let{width:e,height:t,frameRate:r,sampleRate:o,sampleSize:n,channelCount:a}=(i=s.getSettings)==null?void 0:i.call(s),c=s.kind===h.AUDIO?`${o}x${n}@${a}`:`${e}x${t}@${r}`,l=s.stats?` stats: ${JSON.stringify(s.stats).replaceAll('"',"")}`:"";return`${s.id} ${s.readyState} muted:${s.muted} ${s.kind} ${s.label} ${c}${l}`}catch(e){return""}}function rs(s,i){return s.width*s.height===i.width*i.height?1:Qc()&&s.width>s.height&&i.height>i.width?Math.max(i.width/s.height,i.height/s.width,1):Math.max(s.width/i.width,s.height/i.height,1)}function Ai({url:s,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((o,n)=>{if("fetch"in window)return fetch(s,{method:e,body:i,priority:r}).then(c=>c.text()).then(c=>{try{o({data:JSON.parse(c)})}catch(l){o({data:c})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);o({data:c})}catch(c){o({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,s,!0),a.send(i)})}function Yc(s){return p(this,null,function*(){let i=x(),e=JSON.stringify(s);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return C.debug(`compressJSON ${e.length} -> ${a.byteLength} ${x()-i}ms`),a}catch(t){return e}})}var Gf=Object.prototype.hasOwnProperty;var Jt=s=>typeof s=="function",Ci=s=>typeof s=="undefined";var Pn=s=>typeof s=="boolean";var Zc=s=>s.isRemote;var Kc=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 am(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(Kc(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(Gf.call(s,i))return!1;return!0}}return!1}var Wf=0,Jf=1,cm=2;function jf({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,m=-1,f=Wf,g=(D,_)=>p(this,null,function*(){let A=n||this;try{let O=yield s.apply(A,a);u>0&&o&&o.call(this,u),u=0,D(O)}catch(O){let re=()=>{clearTimeout(m),u=0,f=cm,_(O)},Z=()=>{f!==cm&&u<(Jt(c)?c():c)?(u++,f=Jf,Jt(t)&&t.call(this,u,re),m=window.setTimeout(()=>{m=-1,g(D,_)},Jt(l)?l(u):l)):(re(),Jt(r)&&r.call(this,O))};Jt(e)?e.call(this,{error:O,retry:Z,reject:_,retryFuncArgs:a,retriedCount:u}):Z()}});return new Promise(g)}}var jt=jf;var ss=class{constructor(i){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Pn(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),C.log(i,e,Ci(this.userId)||am(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 fs={};fi(fs,{ANDROID_VERSION:()=>id,CHROME_MAJOR_VERSION:()=>dt,CHROME_VERSION:()=>Yn,EDGE_VERSION:()=>xn,EDG_MAJOR_VERSION:()=>rd,EDG_VERSION:()=>Un,FIREFOX_MAJOR_VERSION:()=>no,FIREFOX_VERSION:()=>wn,HUAWEI_VERSION:()=>qn,IE_VERSION:()=>Yf,IOS_MAIN_VERSION:()=>lt,IOS_VERSION:()=>Xt,IPADQQB_VERSION:()=>Jn,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>t_,IS_ANY_SAFARI:()=>Zi,IS_CHROME:()=>ps,IS_CHROME_OS:()=>sd,IS_CHROMIUM_BASE:()=>Ye,IS_DESKTOP_IOS_CHROME:()=>hd,IS_EDG:()=>cs,IS_EDGE:()=>as,IS_ELECTRON:()=>Kf,IS_FIREFOX:()=>ae,IS_HEADLESS_CHROME:()=>dd,IS_HONOR:()=>ad,IS_HUAWEI:()=>nd,IS_HUAWEIBROWSER:()=>fo,IS_IE:()=>mm,IS_IE8:()=>Qf,IS_IOS:()=>Ie,IS_IOS_13_OR_14:()=>md,IS_IOS_15_1:()=>ud,IS_IOS_CHROME:()=>hm,IS_IPAD:()=>ns,IS_IPADQQB:()=>mo,IS_IPAD_PRO:()=>td,IS_IPHONE:()=>Yi,IS_IPOD:()=>um,IS_LINUX:()=>ho,IS_LOCAL:()=>Lt,IS_MAC:()=>Mt,IS_MACQQB:()=>uo,IS_MIBROWSER:()=>po,IS_MQQB:()=>ms,IS_NATIVE_ANDROID:()=>zf,IS_OLD_ANDROID:()=>Xf,IS_OPENHARMONY:()=>cd,IS_OPPOBROWSER:()=>go,IS_SAFARI:()=>Le,IS_SAFARI_15_1:()=>i_,IS_SAMSUNGBROWSER:()=>_o,IS_SOGOU:()=>co,IS_SOGOUM:()=>ao,IS_TBS:()=>kt,IS_UCBROWSER:()=>od,IS_VIVOBROWSER:()=>To,IS_WECHAT:()=>ls,IS_WIN:()=>Ir,IS_WQQB:()=>lo,IS_WX:()=>Zf,IS_X5MQQB:()=>us,IS_XWEB:()=>ds,MACQQB_VERSION:()=>Wn,MI_VERSION:()=>jn,MQQB_VERSION:()=>os,OPENHARMONY_VERSION:()=>e_,OPPO_VERSION:()=>zn,SAFARI_VERSION:()=>Ri,SAMSUNG_VERSION:()=>Xn,SOGOUM_VERSION:()=>Vn,SOGOU_VERSION:()=>Bn,TBS_VERSION:()=>Fn,UA_DATA_STRING:()=>Dt,USER_AGENT:()=>Ot,VIVO_VERSION:()=>Qn,WECHAT_VERSION:()=>Hn,WQQB_VERSION:()=>Gn,XWEB_VERSION:()=>$n,browserInfo:()=>qt,getBrowserInfo:()=>pm,getChromeMajorVersion:()=>hs,getDeviceModel:()=>Ar,getGPUInfo:()=>fd,getOSName:()=>Zn,getOSNumber:()=>So,getOSString:()=>bi,getOSType:()=>r_,getTerminalType:()=>_d,getUserAgentData:()=>Eo,isLocalStorageEnabled:()=>yi,isMobile:()=>pd,isVersionSmallerThan:()=>ld});var Ot=typeof navigator=="undefined"?"":navigator.userAgent,X=s=>new RegExp(s,"i").test(Ot),Ne=s=>{if(X(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=Ot.match(i);if(e&&e[1])return e[1]}return""},ed=s=>{if(X(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=Ot.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},dm=/AppleWebKit\/([\d.]+)/i.exec(Ot),qf=dm?parseFloat(dm[1]):NaN,ns=X("iPad"),td=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),Yi=X("iPhone")&&!ns,um=X("iPod"),Ie=Yi||ns||um||td,pe=X("Android"),id=function(){if(pe){let s=Ot.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(s){let i=s[1]&&parseFloat(s[1]),e=s[2]&&parseFloat(s[2]);if(i&&e)return parseFloat(`${s[1]}.${s[2]}`);if(i)return i}}return NaN}(),Xf=pe&&X("webkit")&&id<2.3,zf=pe&&id<5&&qf<537,ae=X("Firefox"),wn=Ne("Firefox"),no=ed("Firefox"),as=X("Edge"),xn=Ne("Edge"),cs=X("Edg"),Un=Ne("Edg"),rd=ed("Edg"),ao=X("SogouMobileBrowser"),Vn=Ne("SogouMobileBrowser"),co=X("MetaSr\\s"),Bn=Ne("MetaSr\\s"),kt=X("TBS"),Fn=Ne("TBS"),ds=X("XWEB"),$n=Ne("XWEB"),Qf=X("MSIE\\s8\\.0"),mm=X("MSIE\\/\\d+"),Yf=function(){if(mm){let s=/MSIE\s(\d+)\.\d/.exec(Ot),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(Ot)&&/rv:11.0/.test(Ot)&&(i=11),i}return NaN}(),ls=X("(micromessenger|webbrowser)"),Hn=Ne("MicroMessenger"),us=!kt&&X("MQQBrowser")&&X("COVC"),ms=!kt&&X("MQQBrowser")&&!X("COVC"),os=ms||us?Ne("MQQBrowser"):"",lo=!kt&&X(" QQBrowser"),Gn=Ne(" QQBrowser"),uo=!kt&&X("QQBrowserLite"),Wn=Ne("QQBrowserLite"),mo=!kt&&X("MQBHD"),Jn=Ne("MQBHD"),Ir=X("Windows"),Mt=!Ie&&X("MAC OS X"),ho=!pe&&X("Linux"),sd=X("CrOS"),Zf=X("MicroMessenger"),od=X("UCBrowser"),Kf=X("Electron"),po=X("MiuiBrowser"),jn=Ne("MiuiBrowser"),fo=X("HuaweiBrowser"),nd=X("Huawei")||X("HUAWEI"),ad=X("Honor")||X("HONOR"),qn=Ne("HuaweiBrowser"),_o=X("SamsungBrowser"),Xn=Ne("SamsungBrowser"),go=X("HeyTapBrowser"),zn=Ne("HeyTapBrowser"),To=X("VivoBrowser"),Qn=Ne("VivoBrowser"),cd=X("OpenHarmony"),e_=Ne("OpenHarmony"),hs=()=>ed("Chrome"),Ye=X("Chrome"),ps=!as&&!co&&!ao&&!kt&&!ds&&!cs&&!lo&&!po&&!fo&&!_o&&!go&&!To&&Ye,dd=X("HeadlessChrome"),dt=hs(),Yn=Ne("Chrome"),Le=!Ye&&!ms&&!us&&!uo&&!mo&&X("Safari"),Zi=Le||Ie,Ri=Ne("Version"),t_=/Android.*(wv|.0.0.0)/.test(Ot),Xt=(()=>{if(td)return Ri;if(Ie){let s=Ot.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})();function ld(s,i){let e=s.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let o=e[r]||0,n=t[r]||0;if(o<n)return!0;if(o>n)return!1}return!1}var lt=Number(Xt.split(".")[0]),i_=Ri==="15.1",ud=Xt==="15.1",md=(()=>{let s=Number(Xt.split(".")[0]);return s===14||s===13})(),hm=X("CriOS"),hd=hm&&Ri==="11.1.1",Lt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",yi=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),qt=pm();function pm(){let s=new Map([[ae,["Firefox",wn]],[cs,["Edg",Un]],[ps,["Chrome",Yn]],[Le,["Safari",Ri]],[kt,["TBS",Fn]],[ds,["XWEB",$n]],[ls&&Yi,["WeChat",Hn]],[lo,["QQ(Win)",Gn]],[ms,["QQ(Mobile)",os]],[us,["QQ(Mobile X5)",os]],[uo,["QQ(Mac)",Wn]],[mo,["QQ(iPad)",Jn]],[po,["MI",jn]],[fo,["HW",qn]],[_o,["Samsung",Xn]],[go,["OPPO",zn]],[To,["VIVO",Qn]],[as,["EDGE",xn]],[ao,["SogouMobile",Vn]],[co,["Sogou",Bn]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var ce=null;function pd(){return ce&&typeof ce.mobile=="boolean"?ce.mobile:pe||Ie||Yi||ns||cd}var Dt="";function Eo(){return p(this,null,function*(){if(ce)return ce;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return ce=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ce&&!Dt&&(Dt=`UAData: ${ce.platform}/${ce.platformVersion}`,ce.architecture&&ce.bitness&&(Dt+=` ${ce.architecture}/${ce.bitness}`),ce.mobile&&(Dt+=" mobile"),ce.model&&(Dt+=` model: ${ce.model.replace(/\s+/g,"/")}`),ce.fullVersionList&&(Dt+=` ${ce.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),ce}catch(s){return null}})}function fd(){try{let s=document.createElement("canvas"),i=s.getContext("webgl")||s.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(s){return""}}function Ar(){return(ce==null?void 0:ce.model)||""}var lm=new Map([[pe,"Android"],[Ie,"iOS"],[Ir,"Windows"],[Mt,"MacOS"],[ho,"Linux"],[sd,"ChromeOS"]]),Zn=function(){return lm.get(!0)?lm.get(!0):ce?ce.platform:"unknown"};function So(){return Ir?1:pe?2:Mt?3:Ie?4:ho?5:sd?6:0}var bi=()=>{let s=Zn();return s+=`/${qt.name}/${Le?qt.version:qt.version.split(".")[0]}`,ce!=null&&ce.platformVersion&&(s+=`/${ce.platformVersion}`),ce!=null&&ce.architecture&&(s+=`/${ce.architecture}`),s};function _d(){return pe?4:Yi?2:ns?3:Mt?12:Ir?5:ho?13:cd?22:1}function r_(){return pe?"Android":Yi?"iPhone":ns?"iPad":Mt?"Mac":Ir?"Windows":ho?"Linux":"unknown"}var fm=Be(Qe(),1),s_=new fm.default,E=s_;var zt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.LOCAL_AUDIO_STARTED="113",W.LOCAL_AUDIO_STOPPED="114",W.REMOTE_AUDIO_STARTED="115",W.REMOTE_AUDIO_STOPPED="116",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W))(zt||{});var I=zt;var o_="%cTRTC%c%s",n_="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",a_="display: inline",Kn=class Kn{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Xr&&!zs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){E.on(I.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Ct[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),E.on(I.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),E.once(I.JOIN_FAILED,()=>{this.startUpload()}),E.on(I.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(K(t.userId)&&J(t.sdkAppId)){let{userId:r,sdkAppId:o}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:c}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:_n(),sdkAppId:String(a),userId:n,version:ke,log:c.map(l=>l.log).join(`
6
- `)}),a),c.forEach(l=>l.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return jt({retryFunction:()=>Ai({url:Ei(e,Ji.LOG),body:i,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;return e.setTime(qs()),`[${gn(e)}] <${Ct[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(Ct[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(K(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,u)=>`${l} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};if(E.emit(I.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=Ct[i])==null?void 0:c.toLowerCase())||"info";Kn.PRINT_LOG_TAG?console[a](o_,n_,a_,...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 ss(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Ct[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(Kn,"PRINT_LOG_TAG",!(Ie||pe||dd));var gd=Kn,C=new gd;var c_=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)})},Io=c_;var Td=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!yi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let o=JSON.parse(r);if(o&&o.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(yi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){C.warn(i)}}getItem(i){if(!yi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){C.warn(e)}}setItem(i,e){if(yi())try{let t={expiresIn:Date.now()+Sn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){C.warn(t)}}deleteItem(i){if(!yi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return C.warn(e),!1}}clear(){if(yi())try{localStorage.clear()}catch(i){C.warn(i)}}},_s=new Td;var ti={};fi(ti,{HTTPS_API:()=>v_,IS_GET_CAPABILITIES_SUPPORTED:()=>Fd,IS_GET_SETTINGS_SUPPORTED:()=>ei,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Bd,IS_INSERTABLE_STREAM_SUPPORTED:()=>Oi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>ma,IS_RTC_RTP_SENDER_SUPPORTED:()=>Do,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Ss,IS_SEI_SUPPORTED:()=>ko,IS_SPC_SUPPORTED:()=>Es,basis:()=>k_,capabilityCheck:()=>Hd,checkSystemRequirementsInternal:()=>la,decodeSupportStatus:()=>da,encodeSupportStatus:()=>xd,getBrowserInfo:()=>R_,getDisplayResolution:()=>xm,isAddTransceiverSupported:()=>mt,isBrowserSupported:()=>Ud,isGetReceiversSupported:()=>vr,isGetSendersSupported:()=>ir,isGetTransceiversSupported:()=>Kt,isGetUserMediaSupported:()=>Um,isMediaDevicesSupported:()=>ca,isMediaSessionSupported:()=>$m,isMediaStreamTrackProcessorSupported:()=>vo,isReplaceTrackSupported:()=>Vd,isRequestVideoFrameCallbackSupported:()=>Nr,isSIMDSupported:()=>O_,isScreenCaptureApiAvailable:()=>No,isSelectedCandidatePair:()=>tr,isSetParametersSupported:()=>Oo,isSmallStreamAPISupported:()=>Bm,isSmallStreamSupported:()=>ua,isStopTransceiverSupported:()=>D_,isTRTCSupported:()=>y_,isUnifiedPlanDefault:()=>N_,isUsedInHttpProtocol:()=>Di,isWebAudioSupported:()=>Vm,isWebCodecSupported:()=>Fm,isWebCodecsSupported:()=>wm,isWebRTCSupported:()=>$d,isWebTransportSupported:()=>Hm});var Od={};fi(Od,{AUDIO_LEVEL_SCALE:()=>Tt,AudioCodecPipelineType:()=>Nd,AudioDecoderDowngradeState:()=>Ad,AudioPlayerMode:()=>bd,AudioType:()=>Em,BASIC_TYPE:()=>Ki,BannedReason:()=>vd,CONNECTION_CLOSED_REASON:()=>Sd,ClientEvent:()=>_m,CodecType:()=>Rm,ConnectionEvent:()=>Pt,ConnectionState:()=>ut,DECODE_FAILED_ERROR_CODE:()=>Dd,FacingMode:()=>ta,LeaveReason:()=>Cm,LocalTrackEvent:()=>Ao,MULTI_VIDEO_DATA_TYPE:()=>wt,MediaType:()=>Pe,MediaTypeLabel:()=>d_,MonitorEventId:()=>Ro,MutedFlag:()=>Tm,NetworkQualityValue:()=>yd,PlayerState:()=>Cr,ReceiveMode:()=>Am,RemoteStreamType:()=>st,RemoteTrackEvent:()=>Co,RoomEvent:()=>vi,SMALL_MODE:()=>yo,SceneNumber:()=>Id,StreamEvent:()=>gm,StreamType:()=>Im,SubscribeMediaType:()=>Ed,TIMER_TYPE:()=>Yt,TRACK_ACTION:()=>Rd,TRACK_KIND:()=>Cd,TrackEvent:()=>Qt,UserRole:()=>Ze,UserRoleNumber:()=>Rr,VideoCodec:()=>er,VideoCodecPipelineType:()=>ra,VideoContentHint:()=>gs,VideoDecoderDowngradeState:()=>ea,VideoPlayerMode:()=>ia,VideoType:()=>Sm});var Pt=(_=>(_.TRACK_ADDED="track-added",_.TRACK_UPDATED="track-updated",_.TRACK_SUBSCRIBED="track-subscribed",_.STREAM_ADDED="stream-added",_.STREAM_REMOVED="stream-removed",_.STREAM_UPDATED="stream-updated",_.STREAM_PUBLISHED="stream-published",_.STREAM_SUBSCRIBED="stream-subscribed",_.STREAM_UNSUBSCRIBED="stream-unsubscribed",_.STATE_CHANGED="state-changed",_.ERROR="error",_.CONNECTION_STATE_CHANGED="connection-state-changed",_.FIREWALL_RESTRICTION="firewall-restriction",_.SEI_MESSAGE="sei-message",_.CLOSED="closed",_))(Pt||{}),Sd=(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))(Sd||{}),_m=(A=>(A.STREAM_ADDED="stream-added",A.STREAM_REMOVED="stream-removed",A.STREAM_UPDATED="stream-updated",A.STREAM_SUBSCRIBED="stream-subscribed",A.CONNECTION_STATE_CHANGED="connection-state-changed",A.PEER_JOIN="peer-join",A.PEER_LEAVE="peer-leave",A.MUTE_AUDIO="mute-audio",A.MUTE_VIDEO="mute-video",A.UNMUTE_AUDIO="unmute-audio",A.UNMUTE_VIDEO="unmute-video",A.CLIENT_BANNED="client-banned",A.NETWORK_QUALITY="network-quality",A.AUDIO_VOLUME="audio-volume",A.SEI_MESSAGE="sei-message",A.ERROR="error",A))(_m||{}),gm=(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))(gm||{}),Ao=(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))(Ao||{}),Cr=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Cr||{}),vi=(Y=>(Y.PEER_JOIN="peer-join",Y.PEER_LEAVE="peer-leave",Y.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",Y.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",Y.BANNED="banned",Y.NETWORK_QUALITY="network-quality",Y.AUDIO_VOLUME="audio-volume",Y.SEI_MESSAGE="sei-message",Y.ERROR="error",Y.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",Y.REMOTE_PUBLISHED="remote-published",Y.REMOTE_UNPUBLISHED="remote-unpublished",Y.FIREWALL_RESTRICTION="firewall-restriction",Y.HEARTBEAT_REPORT="heartbeat-report",Y.CUSTOM_MESSAGE="custom-message",Y.LAYER_DATA="layerData",Y.FIRST_VIDEO_FRAME="first-video-frame",Y.DUMP="dump",Y.AUDIO_FRAME="audio-frame",Y.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",Y))(vi||{}),Qt=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a.FIRST_VIDEO_FRAME="first-video-frame",a))(Qt||{}),Co=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Co||{}),Tm=(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))(Tm||{}),Id=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Id||{}),Rr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Rr||{}),Ze=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Ze||{}),ut=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(ut||{}),Ad=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Ad||{}),ea=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(ea||{}),Cd=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Cd||{}),Rd=(e=>(e.ADD="add",e.REMOVE="remove",e))(Rd||{}),Pe=(o=>(o[o.NULL=0]="NULL",o[o.AUDIO=1]="AUDIO",o[o.AUX_VIDEO=2]="AUX_VIDEO",o[o.BIG_VIDEO=4]="BIG_VIDEO",o[o.SMALL_VIDEO=8]="SMALL_VIDEO",o))(Pe||{}),d_={1:"audio",2:"auxVideo",4:"video"},Em=(i=>(i[i.opus=111]="opus",i))(Em||{}),Sm=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Sm||{}),Im=(e=>(e.Big="big",e.Small="small",e))(Im||{}),st=(e=>(e.Main="main",e.Aux="auxiliary",e))(st||{}),wt=(o=>(o[o.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",o[o.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",o[o.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",o[o.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",o[o.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",o))(wt||{}),Ro=(k=>(k[k.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",k[k.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",k[k.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",k[k.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",k[k.MUTE_AUDIO=32772]="MUTE_AUDIO",k[k.MUTE_VIDEO=32773]="MUTE_VIDEO",k[k.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",k[k.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",k[k.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",k[k.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",k[k.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",k[k.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",k[k.SWITCH_CAMERA=32780]="SWITCH_CAMERA",k[k.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",k[k.REPLACE_VIDEO=32782]="REPLACE_VIDEO",k[k.REPLACE_AUDIO=32783]="REPLACE_AUDIO",k[k.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",k[k.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",k[k.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",k[k.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",k[k.JOIN=32788]="JOIN",k[k.LEAVE=32789]="LEAVE",k[k.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",k[k.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",k[k.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",k[k.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",k[k.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",k[k.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",k[k.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",k[k.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",k[k.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",k[k.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",k[k.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",k[k.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",k[k.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",k[k.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",k[k.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",k[k.PUBLISH_AUX=32805]="PUBLISH_AUX",k[k.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",k[k.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",k[k.VIDEO_ENCODER=4004]="VIDEO_ENCODER",k[k.VIDEO_DECODER=4005]="VIDEO_DECODER",k))(Ro||{}),yd=(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))(yd||{}),Am=(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))(Am||{}),ta=(e=>(e.user="user",e.environment="environment",e))(ta||{}),ia=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(ia||{}),bd=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(bd||{}),vd=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(vd||{}),Cm=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(Cm||{}),Tt=1e8,Ed=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Ki=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Ki||{}),er=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(er||{}),ra=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ra||{}),Nd=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(Nd||{}),Rm=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(Rm||{}),Dd=(f=>(f[f.SUCCESS=0]="SUCCESS",f[f.FAILED=1]="FAILED",f[f.WEBCODEC_INIT=2]="WEBCODEC_INIT",f[f.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",f[f.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",f[f.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",f[f.WASM_INIT=6]="WASM_INIT",f[f.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",f[f.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",f[f.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",f[f.TEST=10]="TEST",f[f.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",f))(Dd||{}),gs=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(gs||{}),Yt=(o=>(o.INTERVAL="interval",o.TIMEOUT="timeout",o.RAF="raf",o.RIC="ric",o.INTERVAL_IN_WORKER="intervalInWorker",o))(Yt||{}),yo=(e=>(e.CANVAS="canvas",e.API="api",e))(yo||{});var L={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},we={AVOID_REPEATED_CALL(s){return`previous ${s.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Se(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: ${Se(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:s,rule:i,fnName:e,value:t}){return`the min value of ${s||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:s,rule:i,fnName:e,value:t}){return`the max value of ${s||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(s){return`${s.commandDesc||s.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(s){return`SignalChannel setup failure: (errorCode: ${s.errorCode}, errorMsg: ${s.errorMsg} }).`},ERROR_MESSAGE(s){let i=`${s.type} failed`;return s.message&&(i=`${i}: ${s.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(s){return`exchange sdp failed ${s.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(s){return`'${s}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(s){return`'${s}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:s,code:i}){return`Failed to join room - ${s} code: ${i}`},REJOIN_ROOM_FAILED(s){return`reJoin room: ${s.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(s){return`duplicate ${s} stream publishing, please unpublish your prev ${s} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:s,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${s}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(s){return`switchRole failed, errCode: ${s.code} errMsg: ${s.message}.`},CLIENT_BANNED(s){return`client was banned because of ${s.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(s){return`startPublishCDNStream failed, errMsg: ${s.message}.`},STOP_PUBLISH_CDN_FAILED(s){return`stopPublishCDNStream failed, errMsg: ${s.message}.`},INVALID_STREAM_ID(s){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(s){return`cannot replace ${s.kind} track because stream has not ${s.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(s){return`startMixTranscode failed, errMsg: ${s.message}.`},STOP_MIX_TRANSCODE_FAILED(s){return`stopMixTranscode failed, errMsg: ${s.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(s){return`'${s}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:s,fnName:i})=>`'${s}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:s,fnName:i,type:e})=>`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:s=>`${s.media} play failed, browser exception: ${s.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(s){return`${s}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(s){return`${s.signalResponse} failed, response code is ${s.code} , errMsg: ${s.message}.`},CATCH_HANDLER_ERROR({name:s,event:i}){return`an error was caught in ${s}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:s}){return`experimental api ${s} does not exist.`},REPEAT_JOIN:s=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:s}){return`failed to call ${s}() because client was destroyed.`},SEI_NOT_SUPPORT:s=>`not support to sendSEIMessage${s===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:s,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${s?"size":"times"} is over ${s?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(s){return`connection aborted due to: ${s}`},API_CALL_ABORTED(s){let i;return s.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${s.userId} ${s.streamType} stream aborted, reason: remote user ${s.userId} unpublished stream.`:i=`API aborted, reason: ${s.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:s=>`'streamType' is required when 'userId' is not '*', calling ${s}()`};var ym=(s,i)=>i?`${Ht}/${s}/${i}`:`${Ht}/${s}/index.html`;var l_=()=>{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(wc);if(s){s=JSON.parse(s);let i=document.createElement("script");i.type="text/javascript",i.text=s.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function P(s){let{key:i,data:e,link:t,addDocLink:r=!0}=s,o="",n="",a="";ne(we[i])?o=we[i](e):K(we[i])&&(o=we[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=l_();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ne(l[i])?a=l[i](e):K(l[i])&&(a=l[i]));let u=o;return vt()&&(c&&c[i]&&(ne(c[i])?n=c[i](e):K(c[i])&&(n=c[i])),n&&(r?u=`${n}
7
- \u8BF7\u67E5\u770B\u6587\u6863: ${ym("zh-cn",a)}
6
+ `}});var Jh=Oi(Br=>{"use strict";var $s=i_(),kS=s_();Br.write=kS;Br.parse=$s.parse;Br.parseParams=$s.parseParams;Br.parseFmtpConfig=$s.parseFmtpConfig;Br.parsePayloads=$s.parsePayloads;Br.parseRemoteCandidates=$s.parseRemoteCandidates;Br.parseImageAttributes=$s.parseImageAttributes;Br.parseSimulcastStreamList=$s.parseSimulcastStreamList});import WH from"webrtc-adapter";var Wf=gt(Mt());var fm=(O=>(O[O.INVALID_PARAMETER=4096]="INVALID_PARAMETER",O[O.INVALID_OPERATION=4097]="INVALID_OPERATION",O[O.NOT_SUPPORTED=4098]="NOT_SUPPORTED",O[O.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",O[O.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",O[O.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",O[O.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",O[O.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",O[O.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",O[O.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",O[O.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",O[O.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",O[O.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",O[O.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",O[O.CLIENT_BANNED=16448]="CLIENT_BANNED",O[O.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",O[O.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",O[O.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",O[O.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",O[O.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",O[O.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",O[O.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",O[O.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",O[O.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",O[O.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",O[O.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",O[O.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",O[O.API_CALL_ABORTED=16461]="API_CALL_ABORTED",O[O.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",O[O.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",O[O.UNKNOWN=65535]="UNKNOWN",O))(fm||{}),H=fm;var X_=function(s){for(let i in H)if(H[i]===s)return i;return"UNKNOWN"},Qc=class extends Error{constructor({name:e="RtcError",message:t,code:r=H.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${X_(r)} 0x${r.toString(16)}>`,d=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(d);c(this,"code");c(this,"extraCode");c(this,"message");c(this,"originMessage");c(this,"name");c(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=d,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},X=Qc;var _m=new Date().getTime(),Yc=0,gm=function(s){_m=s,Yc=_m-new Date().getTime();let i=new Date;i.setTime(s),z.info(`baseTime from server: ${i} offset: ${Yc}`)},Zo=function(){return new Date().getTime()+Yc},ya=function(){let s=new Date;return s.setTime(Zo()),s.toLocaleString()},ns=function(s){let i=String(s.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${s.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var Jt={};nr(Jt,{bytes2ms:()=>ym,convertObjectNumberToInt:()=>un,copyProperties:()=>Rm,deepClone:()=>hs,deepMerge:()=>Li,delay:()=>hr,fibonacci:()=>fs,formatedTime:()=>Mm,getConstructorName:()=>cn,getContainerFromElement:()=>wm,getEnv:()=>Am,getInternalVersion:()=>km,getLoggerUrl:()=>lr,getMediaStreamTrackInfo:()=>Ha,getMuteStateFromFlag:()=>ur,getNetworkType:()=>ul,getNumNetworkType:()=>ps,getReconnectionTimeout:()=>pi,getStringByteLength:()=>ln,getTurnServer:()=>Om,getUint32Version:()=>Ba,getValueType:()=>lt,getViewListFromView:()=>Ks,glog:()=>pl,ipv4ToUint32:()=>Zs,isArray:()=>tt,isAudioWorkletSupported:()=>Dm,isBoolean:()=>Qe,isConstructor:()=>Qs,isEmpty:()=>Ys,isFunction:()=>Fe,isLangChinese:()=>mi,isMediaStreamTrack:()=>vm,isNumber:()=>De,isObject:()=>xi,isOverseaSdkAppId:()=>ms,isPlainObject:()=>Ht,isPortrait:()=>Va,isPromise:()=>Wr,isRemoteTrack:()=>Nm,isString:()=>Oe,isUndefined:()=>M,loadImage:()=>eo,ms2bytes:()=>bm,ms2samples:()=>ml,normalizeUrl:()=>Fa,performanceNow:()=>le,promiseAny:()=>_s,samples2ms:()=>hl,setNetworkType:()=>Pa,stringify:()=>oi,stringifyIncludeValue:()=>Ua,throttlePromise:()=>$a});var ll={};nr(ll,{AUDIO_MUTE_BIT:()=>wa,AUDIO_STAT_BIT:()=>Hr,AUX_STAT_BIT:()=>ds,AUX_STREAM_MSID:()=>rl,BACKEND_ENV:()=>Oa,BASE_DOC_URL:()=>wi,BASE_HOST:()=>Em,CAPABILITIES_KEYS:()=>La,CLASS_NAME:()=>gg,CLOUD_CONSOLE_URL:()=>K_,CROSS_ROOM_BIT:()=>il,DATA_FREEZE_TIMING:()=>xa,DEFAULT_ASSETS_URL:()=>ba,DOC_URL:()=>eg,DTLS_STATE_UNKNOWN:()=>hi,ENV_NAME:()=>ar,EXCHANGE_SDP_TIMEOUT:()=>dl,IS_WORKER:()=>js,IS_WORKLET:()=>en,KIBANA_EVENT:()=>Ft,LOCAL_STREAM_PUBLISH_STATE:()=>Sm,LOGGER_CMD_TYPE:()=>$r,LOGGER_DOMAIN:()=>Kc,LOGGER_DOMAIN_OVERSEA:()=>el,LOG_LEVEL:()=>ri,LOG_LEVEL_NAME:()=>Tg,MAIN_STREAM_MSID:()=>sn,MAX_RTT:()=>an,MICROPHONE_COMMUNICATIONS:()=>Eg,MICROPHONE_DEFAULT:()=>us,MUTE_ALL_BIT:()=>rg,NAME:()=>S,NETWORK_TYPE:()=>va,NOT_SUPPORTED_H264:()=>cs,PAUSED_RETRY_COUNT:()=>ls,PEERCONNECTION_CONNECTING_TIMEOUT:()=>on,PEER_CONNECTION_STATE:()=>Je,PEER_LEAVE_REASON:()=>cl,RECOVER_CAPTURE_INTERVAL:()=>Xs,REMOTE_STREAM_TYPE_AUX:()=>ol,REMOTE_STREAM_TYPE_MAIN:()=>sl,RENDER_FREEZE_TIMING:()=>mg,SCHEDULE_DOMAIN:()=>cr,SCHEDULE_TIMEOUT:()=>_g,SDP_SEMANTICS_PLAN_B:()=>Js,SDP_SEMANTICS_UNIFIED_PLAN:()=>Gr,SECOND_HOST:()=>Y_,SIGNAL_PING_PONG_INTERVAL:()=>ig,SIGNAL_PING_TIMEOUT:()=>tg,SIGNAL_RECONNECTION_COUNT:()=>ug,SMALL_STAT_BIT:()=>rn,SPEAKER_DEFAULT:()=>nn,STORAGE_EXPIRES_TIME:()=>Na,STREAM_TYPE_BIG:()=>pg,STREAM_TYPE_SMALL:()=>fg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>qs,SYNC_USER_LIST_INTERVAL:()=>hg,Scene:()=>Mi,THIRD_HOST:()=>Z_,TRANSPORT_DIRECTION:()=>ke,TRTC_ERROR_ASSISTANCE:()=>tl,TRTC_QUALITY_BAD:()=>dg,TRTC_QUALITY_DISCONNECTED:()=>lg,TRTC_QUALITY_EXCELLENT:()=>og,TRTC_QUALITY_GOOD:()=>ng,TRTC_QUALITY_POOR:()=>ag,TRTC_QUALITY_UNKNOWN:()=>sg,TRTC_QUALITY_VERY_BAD:()=>cg,UPDATE_OFFER_TIMEOUT:()=>al,VIDEO_MUTE_BIT:()=>Ma,VIDEO_STAT_BIT:()=>Fr,audioProfileMap:()=>Da,getRetryCount:()=>dr,getScriptDir:()=>Q_,innerVersion:()=>Ko,loggerProxy:()=>tn,screenProfileMap:()=>ka,setLoggerProxy:()=>as,setRetryCount:()=>nl,setVersion:()=>Zc,version:()=>Rt,videoProfileMap:()=>si});var Ko="4.15.00.1600",Rt="5.0.0";function Zc(s){Rt=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));Ko=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var js=typeof importScripts!="undefined",en=typeof registerProcessor!="undefined",Q_=()=>{let s=js?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},tn="",as=s=>tn=s,Em="web.sdk.qcloud.com",Y_="web.sdk.tencent.cn",Z_="web.sdk.cloud.tencent.cn",K_="https://console.cloud.tencent.com/trtc",wi=`https://${Em}/trtc/webrtc/v5/doc`,ba="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",eg=`${wi}/zh-cn/`,Kc="https://yun.tim.qq.com",el="https://apisgp.my-imcloud.com",tl="trtc_error_assistance",$r={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ar={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},ri=(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))(ri||{}),tg=18e3,ig=2e3,va={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Na=7*24*3600*1e3,Da={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}},si={"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}},ka={"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}},S={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},ke={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Oa={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Mi=(e=>(e.LIVE="live",e.RTC="rtc",e))(Mi||{}),Fr=1,rn=2,ds=4,Hr=8,wa=64,Ma=16,rg=112,il=128,sn="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",rl="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",sl=S.MAIN,ol=S.AUXILIARY,sg=0,og=1,ng=2,ag=3,dg=4,cg=5,lg=6,hi="unknown",Je={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Tm=1/0;function nl(s){Tm=s}function dr(){return Tm}var ug=30,Ft={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"},hg=1e4,al=1e4,dl=1e4,Gr="unified-plan",Js="plan-b",cs=1028,Sm=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Sm||{}),xa=500,mg=1e3,pg=S.BIG,fg=S.SMALL,on=10*1e3,cr={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},_g=2e3,gg={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},ls=5,us="default",nn=us,Eg="communications",Tg=Object.keys(ri),cl=["normal leave","timeout leave","kick","role change"],qs=10,Xs=2e3,La=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],an=10*1e3;var Am=function(){return new URLSearchParams(location.search).get("trtc_env")||""},ms=s=>Number(s)<14e8,lr=function(s,i){let e;tn?e=tn:e=ms(s)?el:Kc;let t=Math.floor(Math.random()*Xo(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},dn="unknown";function ul(){if(dn!=="unknown")return dn;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&&(dn=Cm(t,r)),dn}function Cm(s,i){if(va[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Pa(s){dn=Cm(s)}function ps(){return va[ul()]}function Rm(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 ym(s,i=48e3){return hl(s/4,i)}function hl(s,i=48e3){return s*1e3/i}function bm(s,i=48e3){return ml(s,i)*4}function ml(s,i=48e3){return s*i/1e3}var pl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},mi=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},Ht=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 fs(s,i=1,e=1){return s<=1?e:fs(s-1,e,i+e)}function pi(s){return s>8?30*1e3:fs(s)*1e3}function lt(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Fe=s=>typeof s=="function",M=s=>typeof s=="undefined",Oe=s=>typeof s=="string",De=s=>typeof s=="number",Qe=s=>typeof s=="boolean",xi=s=>lt(s)==="object",tt=s=>lt(s)==="array",vm=s=>lt(s)==="MediaStreamTrack".toLowerCase(),Nm=s=>s.isRemote,Wr=s=>lt(s)==="promise",Qs=s=>Fe(s)&&s.prototype.constructor===s,cn=s=>Qs(s)?s.prototype.constructor.name:"",Dm=typeof AudioWorkletNode!="undefined";function _s(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 le(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Im=s=>+s<10?`0${s}`:s,km=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=Im(e[1])+Im(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Sg=Object.prototype.hasOwnProperty,{toString:dI}=Object.prototype;function Ys(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(Ht(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(Sg.call(s,i))return!1;return!0}}return!1}function ur(s,i){return{userId:i,hasAudio:!!(s&Hr),hasVideo:!!(s&Fr),hasAuxiliary:!!(s&ds),hasSmall:!!(s&rn),audioMuted:!!(s&wa),videoMuted:!!(s&Ma),audioAvailable:!!(s&Hr)&&!(s&wa),videoAvailable:!!(s&Fr)&&!(s&Ma)}}function Om(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!M(s.username)&&!M(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",M(s.credentialType)||(i.credentialType=s.credentialType)),i}function Zs(s,i=!0){if(!Oe(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 Li=function(s,i,e,t){if(!(xi(s)&&xi(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,d=o.length;a<d;a++)if(n=o[a],!(M(i[n])||e&&e.includes(n)))if(xi(s[n])&&xi(i[n]))r+=Li(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=hs(i[n]),r+=1)}return r};function hs(s){if(tt(s)){let i=[];return s.forEach((e,t)=>{i[t]=hs(e)}),i}if(xi(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=hs(s[e])}),i}return s}var Ks=s=>{let i=[];if(tt(s))i=[...s];else if(Oe(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},wm=s=>Oe(s)?document.getElementById(s):s,Ig=s=>{let i=d=>d<10?`0${d}`:`${d}`,e=s.getFullYear(),t=s.getMonth()+1,r=s.getDate(),o=i(s.getHours()),n=i(s.getMinutes()),a=i(s.getSeconds());return`${e}/${t}/${r} ${o}:${n}:${a}`},Mm=()=>Ig(new Date);function oi(s,{keysToInclude:i,keysToExclude:e}){try{if(tt(s))return`[${s.map(n=>oi(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Ht(s)||!tt(i)&&!tt(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]=Ht(s[n])||tt(s[n])?JSON.parse(oi(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Ua(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),oi(s,{keysToInclude:e})}function ln(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Va=()=>{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},eo=s=>A(void 0,null,function*(){return new Promise((i,e)=>{let t;if(Oe(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 X({code:H.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),Ba=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},un=s=>(Object.keys(s).forEach(i=>{De(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(Ht(s[i])||tt(s[i]))&&un(s[i])}),s);function hr(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function $a(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function Fa(s){return s.replace(/(^|[^:])\/{2,}/g,"$1/")}function Ha(s){var i;try{let{width:e,height:t,frameRate:r,sampleRate:o,sampleSize:n,channelCount:a}=(i=s.getSettings)==null?void 0:i.call(s),d=s.kind===S.AUDIO?`${o}x${n}@${a}`:`${e}x${t}@${r}`,l=s.stats?` stats: ${JSON.stringify(s.stats).replaceAll('"',"")}`:"";return`${s.id} ${s.readyState} muted:${s.muted} ${s.kind} ${s.label} ${d}${l}`}catch(e){return""}}function mr({url:s,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((o,n)=>{if("fetch"in window)return fetch(s,{method:e,body:i,priority:r}).then(d=>d.text()).then(d=>{try{o({data:JSON.parse(d)})}catch(l){o({data:d})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let d=JSON.parse(a.response);o({data:d})}catch(d){o({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,s,!0),a.send(i)})}function fl(s){return A(this,null,function*(){let i=le(),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 z.debug(`compressJSON ${e.length} -> ${a.byteLength} ${le()-i}ms`),a}catch(t){return e}})}var Ag=Object.prototype.hasOwnProperty;var Pi=s=>typeof s=="function",pr=s=>typeof s=="undefined";var Ga=s=>typeof s=="boolean";var _l=s=>s.isRemote;var Cg=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 xm(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(Cg(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(Ag.call(s,i))return!1;return!0}}return!1}var Rg=0,yg=1,Lm=2;function bg({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:d=5,timeout:l=1e3}=i,h=0,u=-1,m=Rg,p=(g,f)=>A(this,null,function*(){let T=n||this;try{let I=yield s.apply(T,a);h>0&&o&&o.call(this,h),h=0,g(I)}catch(I){let v=()=>{clearTimeout(u),h=0,m=Lm,f(I)},b=()=>{m!==Lm&&h<(Pi(d)?d():d)?(h++,m=yg,Pi(t)&&t.call(this,h,v),u=window.setTimeout(()=>{u=-1,p(g,f)},Pi(l)?l(h):l)):(v(),Pi(r)&&r.call(this,I))};Pi(e)?e.call(this,{error:I,retry:b,reject:f,retryFuncArgs:a,retriedCount:h}):b()}});return new Promise(p)}}var Ui=bg;var to=class{constructor(i){c(this,"userId");c(this,"remoteUserId");c(this,"id");c(this,"sdkAppId");c(this,"type");c(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Ga(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}`:""}]`),z.log(i,e,pr(this.userId)||xm(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 mo={};nr(mo,{ANDROID_VERSION:()=>Tl,CHROME_MAJOR_VERSION:()=>qt,CHROME_VERSION:()=>nd,EDGE_VERSION:()=>za,EDG_MAJOR_VERSION:()=>Sl,EDG_VERSION:()=>ja,FIREFOX_MAJOR_VERSION:()=>hn,FIREFOX_VERSION:()=>Wa,HUAWEI_VERSION:()=>id,IE_VERSION:()=>Og,IOS_MAIN_VERSION:()=>Xt,IOS_VERSION:()=>Bi,IPADQQB_VERSION:()=>ed,IS_ANDROID:()=>ze,IS_ANDROID_WEBVIEW:()=>Lg,IS_ANY_SAFARI:()=>jr,IS_CHROME:()=>ho,IS_CHROME_OS:()=>Il,IS_CHROMIUM_BASE:()=>xt,IS_DESKTOP_IOS_CHROME:()=>kl,IS_EDG:()=>oo,IS_EDGE:()=>so,IS_ELECTRON:()=>Mg,IS_FIREFOX:()=>Ue,IS_HEADLESS_CHROME:()=>bl,IS_HONOR:()=>Rl,IS_HUAWEI:()=>Cl,IS_HUAWEIBROWSER:()=>Sn,IS_IE:()=>Bm,IS_IE8:()=>kg,IS_IOS:()=>Ye,IS_IOS_13_OR_14:()=>Dl,IS_IOS_15_1:()=>Nl,IS_IOS_CHROME:()=>$m,IS_IPAD:()=>ro,IS_IPADQQB:()=>gn,IS_IPAD_PRO:()=>El,IS_IPHONE:()=>zr,IS_IPOD:()=>Vm,IS_LINUX:()=>En,IS_LOCAL:()=>Ti,IS_MAC:()=>Ei,IS_MACQQB:()=>_n,IS_MIBROWSER:()=>Tn,IS_MQQB:()=>lo,IS_NATIVE_ANDROID:()=>Dg,IS_OLD_ANDROID:()=>Ng,IS_OPENHARMONY:()=>yl,IS_OPPOBROWSER:()=>An,IS_SAFARI:()=>pt,IS_SAFARI_15_1:()=>Pg,IS_SAMSUNGBROWSER:()=>In,IS_SOGOU:()=>pn,IS_SOGOUM:()=>mn,IS_TBS:()=>gi,IS_UCBROWSER:()=>Al,IS_VIVOBROWSER:()=>Cn,IS_WECHAT:()=>ao,IS_WIN:()=>gs,IS_WQQB:()=>fn,IS_WX:()=>wg,IS_X5MQQB:()=>co,IS_XWEB:()=>no,MACQQB_VERSION:()=>Ka,MI_VERSION:()=>td,MQQB_VERSION:()=>io,OPENHARMONY_VERSION:()=>xg,OPPO_VERSION:()=>sd,SAFARI_VERSION:()=>fr,SAMSUNG_VERSION:()=>rd,SOGOUM_VERSION:()=>Ja,SOGOU_VERSION:()=>qa,TBS_VERSION:()=>Xa,UA_DATA_STRING:()=>fi,USER_AGENT:()=>_i,VIVO_VERSION:()=>od,WECHAT_VERSION:()=>Ya,WQQB_VERSION:()=>Za,XWEB_VERSION:()=>Qa,browserInfo:()=>Vi,getBrowserInfo:()=>Fm,getChromeMajorVersion:()=>uo,getDeviceModel:()=>Ts,getGPUInfo:()=>wl,getOSName:()=>ad,getOSNumber:()=>Rn,getOSString:()=>gr,getOSType:()=>Ug,getTerminalType:()=>Ml,getUserAgentData:()=>Es,isLocalStorageEnabled:()=>_r,isMobile:()=>Ol,isVersionSmallerThan:()=>vl});var _i=typeof navigator=="undefined"?"":navigator.userAgent,ye=s=>new RegExp(s,"i").test(_i),ut=s=>{if(ye(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=_i.match(i);if(e&&e[1])return e[1]}return""},gl=s=>{if(ye(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=_i.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Pm=/AppleWebKit\/([\d.]+)/i.exec(_i),vg=Pm?parseFloat(Pm[1]):NaN,ro=ye("iPad"),El=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ye("Macintosh"),zr=ye("iPhone")&&!ro,Vm=ye("iPod"),Ye=zr||ro||Vm||El,ze=ye("Android"),Tl=function(){if(ze){let s=_i.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}(),Ng=ze&&ye("webkit")&&Tl<2.3,Dg=ze&&Tl<5&&vg<537,Ue=ye("Firefox"),Wa=ut("Firefox"),hn=gl("Firefox"),so=ye("Edge"),za=ut("Edge"),oo=ye("Edg"),ja=ut("Edg"),Sl=gl("Edg"),mn=ye("SogouMobileBrowser"),Ja=ut("SogouMobileBrowser"),pn=ye("MetaSr\\s"),qa=ut("MetaSr\\s"),gi=ye("TBS"),Xa=ut("TBS"),no=ye("XWEB"),Qa=ut("XWEB"),kg=ye("MSIE\\s8\\.0"),Bm=ye("MSIE\\/\\d+"),Og=function(){if(Bm){let s=/MSIE\s(\d+)\.\d/.exec(_i),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(_i)&&/rv:11.0/.test(_i)&&(i=11),i}return NaN}(),ao=ye("(micromessenger|webbrowser)"),Ya=ut("MicroMessenger"),co=!gi&&ye("MQQBrowser")&&ye("COVC"),lo=!gi&&ye("MQQBrowser")&&!ye("COVC"),io=lo||co?ut("MQQBrowser"):"",fn=!gi&&ye(" QQBrowser"),Za=ut(" QQBrowser"),_n=!gi&&ye("QQBrowserLite"),Ka=ut("QQBrowserLite"),gn=!gi&&ye("MQBHD"),ed=ut("MQBHD"),gs=ye("Windows"),Ei=!Ye&&ye("MAC OS X"),En=!ze&&ye("Linux"),Il=ye("CrOS"),wg=ye("MicroMessenger"),Al=ye("UCBrowser"),Mg=ye("Electron"),Tn=ye("MiuiBrowser"),td=ut("MiuiBrowser"),Sn=ye("HuaweiBrowser"),Cl=ye("Huawei")||ye("HUAWEI"),Rl=ye("Honor")||ye("HONOR"),id=ut("HuaweiBrowser"),In=ye("SamsungBrowser"),rd=ut("SamsungBrowser"),An=ye("HeyTapBrowser"),sd=ut("HeyTapBrowser"),Cn=ye("VivoBrowser"),od=ut("VivoBrowser"),yl=ye("OpenHarmony"),xg=ut("OpenHarmony"),uo=()=>gl("Chrome"),xt=ye("Chrome"),ho=!so&&!pn&&!mn&&!gi&&!no&&!oo&&!fn&&!Tn&&!Sn&&!In&&!An&&!Cn&&xt,bl=ye("HeadlessChrome"),qt=uo(),nd=ut("Chrome"),pt=!xt&&!lo&&!co&&!_n&&!gn&&ye("Safari"),jr=pt||Ye,fr=ut("Version"),Lg=/Android.*(wv|.0.0.0)/.test(_i),Bi=(()=>{if(El)return fr;if(Ye){let s=_i.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})();function vl(s,i){let e=s.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let o=e[r]||0,n=t[r]||0;if(o<n)return!0;if(o>n)return!1}return!1}var Xt=Number(Bi.split(".")[0]),Pg=fr==="15.1",Nl=Bi==="15.1",Dl=(()=>{let s=Number(Bi.split(".")[0]);return s===14||s===13})(),$m=ye("CriOS"),kl=$m&&fr==="11.1.1",Ti=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",_r=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),Vi=Fm();function Fm(){let s=new Map([[Ue,["Firefox",Wa]],[oo,["Edg",ja]],[ho,["Chrome",nd]],[pt,["Safari",fr]],[gi,["TBS",Xa]],[no,["XWEB",Qa]],[ao&&zr,["WeChat",Ya]],[fn,["QQ(Win)",Za]],[lo,["QQ(Mobile)",io]],[co,["QQ(Mobile X5)",io]],[_n,["QQ(Mac)",Ka]],[gn,["QQ(iPad)",ed]],[Tn,["MI",td]],[Sn,["HW",id]],[In,["Samsung",rd]],[An,["OPPO",sd]],[Cn,["VIVO",od]],[so,["EDGE",za]],[mn,["SogouMobile",Ja]],[pn,["Sogou",qa]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var Ve=null;function Ol(){return Ve&&typeof Ve.mobile=="boolean"?Ve.mobile:ze||Ye||zr||ro||yl}var fi="";function Es(){return A(this,null,function*(){if(Ve)return Ve;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return Ve=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Ve&&!fi&&(fi=`UAData: ${Ve.platform}/${Ve.platformVersion}`,Ve.architecture&&Ve.bitness&&(fi+=` ${Ve.architecture}/${Ve.bitness}`),Ve.mobile&&(fi+=" mobile"),Ve.model&&(fi+=` model: ${Ve.model.replace(/\s+/g,"/")}`),Ve.fullVersionList&&(fi+=` ${Ve.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),Ve}catch(s){return null}})}function wl(){try{let s=document.createElement("canvas"),i=s.getContext("webgl")||s.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(s){return""}}function Ts(){return(Ve==null?void 0:Ve.model)||""}var Um=new Map([[ze,"Android"],[Ye,"iOS"],[gs,"Windows"],[Ei,"MacOS"],[En,"Linux"],[Il,"ChromeOS"]]),ad=function(){return Um.get(!0)?Um.get(!0):Ve?Ve.platform:"unknown"};function Rn(){return gs?1:ze?2:Ei?3:Ye?4:En?5:Il?6:0}var gr=()=>{let s=ad();return s+=`/${Vi.name}/${pt?Vi.version:Vi.version.split(".")[0]}`,Ve!=null&&Ve.platformVersion&&(s+=`/${Ve.platformVersion}`),Ve!=null&&Ve.architecture&&(s+=`/${Ve.architecture}`),s};function Ml(){return ze?4:zr?2:ro?3:Ei?12:gs?5:En?13:yl?22:1}function Ug(){return ze?"Android":zr?"iPhone":ro?"iPad":Ei?"Mac":gs?"Windows":En?"Linux":"unknown"}var Hm=gt(Mt(),1),Vg=new Hm.default,x=Vg;var ni=(k=>(k.ROOM_DESTROY="1",k.JOIN_START="21",k.JOIN_SCHEDULE_SUCCESS="22",k.JOIN_SIGNAL_CONNECTION_START="23",k.JOIN_SIGNAL_CONNECTION_END="24",k.JOIN_SEND_CMD="25",k.JOIN_RECEIVED_CMD_RES="26",k.JOIN_SUCCESS="27",k.JOIN_FAILED="28",k.LEAVE_START="51",k.LEAVE_SEND_CMD="52",k.LEAVE_SUCCESS="53",k.PUBLISH_START="61",k.SEND_FIRST_VIDEO_FRAME="62",k.PUBLISH_FAILED="63",k.SUBSCRIBE_START="81",k.SUBSCRIBE_SUCCESS="82",k.SUBSCRIBE_FAILED="84",k.UNSUBSCRIBE_SUCCESS="83",k.LOCAL_TRACK_CAPTURE_START="101",k.LOCAL_TRACK_CAPTURE_SUCCESS="102",k.LOCAL_TRACK_CAPTURE_FAILED="103",k.LOCAL_TRACK_PUBLISHED="104",k.LOCAL_TRACK_UNPUBLISHED="105",k.LOCAL_TRACK_REPLACED="106",k.SWITCH_DEVICE_SUCCESS="107",k.TRACK_MUTED="108",k.TRACK_UNMUTED="109",k.REMOTE_TRACK_SUBSCRIBED="110",k.REMOTE_TRACK_UNSUBSCRIBED="111",k.LOCAL_TRACK_RECAPTURE="112",k.PLAY_TRACK_START="151",k.PLAYER_STATE_CHANGED="152",k.VIDEO_LOADED_DATA="153",k.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",k.SIGNAL_CONNECTION_STATE_CHANGED="201",k.PEER_CONNECTION_STATE_CHANGED="202",k.SINGLE_CONNECTION_STAT="203",k.SPC_RECONNECTED="204",k.HEARTBEAT_REPORT="251",k.RECEIVED_PUBLISHED_USER_LIST="252",k.REMOTE_PUBLISH_STATE_CHANGED="253",k.AUDIO_LEVEL_INTERVAL="260",k.NETWORK_QUALITY="261",k.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",k.QUALITY_LIMITATION_CHANGED="263",k.LOG="264",k.AUDIO_PROCESSOR_DEBUG="265",k.AUDIO_PROCESSOR_REFERENCE_CHANGED="266",k))(ni||{});var B=ni;var Bg="%cTRTC%c%s",$g="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Fg="display: inline",dd=class dd{constructor(){c(this,"_isEnableUploadLog",!0);c(this,"_localJoinedUser",new Map);c(this,"_queue",[]);c(this,"_timeoutId",-1);c(this,"_logLevel",1);c(this,"_logLevelToUpload",2);!js&&!en&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){x.on(B.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&ri[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),x.on(B.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),x.once(B.JOIN_FAILED,()=>{this.startUpload()}),x.on(B.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(Oe(t.userId)&&De(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 A(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:d}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:ya(),sdkAppId:String(a),userId:n,version:Rt,log:d.map(l=>l.log).join(`
7
+ `)}),a),d.forEach(l=>l.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Ui({retryFunction:()=>mr({url:lr(e,$r.LOG),body:i,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;return e.setTime(Zo()),`[${ns(e)}] <${ri[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){M(ri[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(Oe(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,o){var d;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,h)=>`${l} ${this.logChunkToString(h)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};if(x.emit(B.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((d=ri[i])==null?void 0:d.toLowerCase())||"info";dd.PRINT_LOG_TAG?console[a](Bg,$g,Fg,...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 to(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;ri[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};c(dd,"PRINT_LOG_TAG",!(Ye||ze||bl));var xl=dd,z=new xl;var Hg=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)})},yn=Hg;var Ll=class{constructor(){c(this,"_prefix","TRTC");c(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!_r())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let o=JSON.parse(r);if(o&&o.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(_r())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){z.warn(i)}}getItem(i){if(!_r())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){z.warn(e)}}setItem(i,e){if(_r())try{let t={expiresIn:Date.now()+Na,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){z.warn(t)}}deleteItem(i){if(!_r())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return z.warn(e),!1}}clear(){if(_r())try{localStorage.clear()}catch(i){z.warn(i)}}},po=new Ll;var Wi={};nr(Wi,{HTTPS_API:()=>aE,IS_GET_CAPABILITIES_SUPPORTED:()=>su,IS_GET_SETTINGS_SUPPORTED:()=>Gi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>ru,IS_INSERTABLE_STREAM_SUPPORTED:()=>Ar,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Id,IS_RTC_RTP_SENDER_SUPPORTED:()=>wn,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Sd,IS_SEI_SUPPORTED:()=>xn,IS_SPC_SUPPORTED:()=>go,basis:()=>uE,capabilityCheck:()=>nu,checkSystemRequirementsInternal:()=>Td,decodeSupportStatus:()=>Ed,encodeSupportStatus:()=>Kl,getBrowserInfo:()=>sE,getDisplayResolution:()=>cp,isAddTransceiverSupported:()=>Yt,isBrowserSupported:()=>eu,isGetReceiversSupported:()=>Rs,isGetSendersSupported:()=>Qr,isGetTransceiversSupported:()=>Hi,isGetUserMediaSupported:()=>lp,isMediaDevicesSupported:()=>gd,isMediaSessionSupported:()=>pp,isMediaStreamTrackProcessorSupported:()=>tu,isReplaceTrackSupported:()=>iu,isRequestVideoFrameCallbackSupported:()=>ys,isSIMDSupported:()=>lE,isScreenCaptureApiAvailable:()=>kn,isSelectedCandidatePair:()=>Xr,isSetParametersSupported:()=>Mn,isSmallStreamAPISupported:()=>hp,isSmallStreamSupported:()=>On,isStopTransceiverSupported:()=>cE,isTRTCSupported:()=>oE,isUnifiedPlanDefault:()=>dE,isUsedInHttpProtocol:()=>Ir,isWebAudioSupported:()=>up,isWebCodecSupported:()=>mp,isWebCodecsSupported:()=>dp,isWebRTCSupported:()=>ou,isWebTransportSupported:()=>fp});var Jl={};nr(Jl,{AUDIO_LEVEL_SCALE:()=>ai,AudioCodecPipelineType:()=>zl,AudioDecoderDowngradeState:()=>Bl,AudioPlayerMode:()=>Gl,AudioType:()=>jm,BASIC_TYPE:()=>Jr,BannedReason:()=>Wl,CONNECTION_CLOSED_REASON:()=>Ul,ClientEvent:()=>Gm,CodecType:()=>Ym,ConnectionEvent:()=>Si,ConnectionState:()=>Qt,DECODE_FAILED_ERROR_CODE:()=>jl,FacingMode:()=>ld,LeaveReason:()=>Qm,LocalTrackEvent:()=>bn,MULTI_VIDEO_DATA_TYPE:()=>Ii,MediaType:()=>Et,MediaTypeLabel:()=>Gg,MonitorEventId:()=>Nn,MutedFlag:()=>zm,NetworkQualityValue:()=>Hl,PlayerState:()=>Ss,ReceiveMode:()=>Xm,RemoteStreamType:()=>Pt,RemoteTrackEvent:()=>vn,RoomEvent:()=>Er,SceneNumber:()=>Vl,StreamEvent:()=>Wm,StreamType:()=>qm,SubscribeMediaType:()=>Pl,TIMER_TYPE:()=>$i,TRACK_ACTION:()=>Fl,TRACK_KIND:()=>$l,TrackEvent:()=>Tr,UserRole:()=>Lt,UserRoleNumber:()=>Is,VideoCodec:()=>qr,VideoCodecPipelineType:()=>hd,VideoContentHint:()=>fo,VideoDecoderDowngradeState:()=>cd,VideoPlayerMode:()=>ud,VideoType:()=>Jm});var Si=(f=>(f.TRACK_ADDED="track-added",f.TRACK_UPDATED="track-updated",f.TRACK_SUBSCRIBED="track-subscribed",f.STREAM_ADDED="stream-added",f.STREAM_REMOVED="stream-removed",f.STREAM_UPDATED="stream-updated",f.STREAM_PUBLISHED="stream-published",f.STREAM_SUBSCRIBED="stream-subscribed",f.STREAM_UNSUBSCRIBED="stream-unsubscribed",f.STATE_CHANGED="state-changed",f.ERROR="error",f.CONNECTION_STATE_CHANGED="connection-state-changed",f.FIREWALL_RESTRICTION="firewall-restriction",f.SEI_MESSAGE="sei-message",f.CLOSED="closed",f))(Si||{}),Ul=(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))(Ul||{}),Gm=(T=>(T.STREAM_ADDED="stream-added",T.STREAM_REMOVED="stream-removed",T.STREAM_UPDATED="stream-updated",T.STREAM_SUBSCRIBED="stream-subscribed",T.CONNECTION_STATE_CHANGED="connection-state-changed",T.PEER_JOIN="peer-join",T.PEER_LEAVE="peer-leave",T.MUTE_AUDIO="mute-audio",T.MUTE_VIDEO="mute-video",T.UNMUTE_AUDIO="unmute-audio",T.UNMUTE_VIDEO="unmute-video",T.CLIENT_BANNED="client-banned",T.NETWORK_QUALITY="network-quality",T.AUDIO_VOLUME="audio-volume",T.SEI_MESSAGE="sei-message",T.ERROR="error",T))(Gm||{}),Wm=(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))(Wm||{}),bn=(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))(bn||{}),Ss=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Ss||{}),Er=(w=>(w.PEER_JOIN="peer-join",w.PEER_LEAVE="peer-leave",w.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",w.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",w.BANNED="banned",w.NETWORK_QUALITY="network-quality",w.AUDIO_VOLUME="audio-volume",w.SEI_MESSAGE="sei-message",w.ERROR="error",w.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",w.REMOTE_PUBLISHED="remote-published",w.REMOTE_UNPUBLISHED="remote-unpublished",w.FIREWALL_RESTRICTION="firewall-restriction",w.HEARTBEAT_REPORT="heartbeat-report",w.CUSTOM_MESSAGE="custom-message",w.LAYER_DATA="layerData",w.FIRST_VIDEO_FRAME="first-video-frame",w.DUMP="dump",w.AUDIO_FRAME="audio-frame",w.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",w))(Er||{}),Tr=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a.FIRST_VIDEO_FRAME="first-video-frame",a))(Tr||{}),vn=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(vn||{}),zm=(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))(zm||{}),Vl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Vl||{}),Is=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Is||{}),Lt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Lt||{}),Qt=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(Qt||{}),Bl=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Bl||{}),cd=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(cd||{}),$l=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))($l||{}),Fl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Fl||{}),Et=(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))(Et||{}),Gg={1:"audio",2:"auxVideo",4:"video"},jm=(i=>(i[i.opus=111]="opus",i))(jm||{}),Jm=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Jm||{}),qm=(e=>(e.Big="big",e.Small="small",e))(qm||{}),Pt=(e=>(e.Main="main",e.Aux="auxiliary",e))(Pt||{}),Ii=(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))(Ii||{}),Nn=(W=>(W[W.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",W[W.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",W[W.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",W[W.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",W[W.MUTE_AUDIO=32772]="MUTE_AUDIO",W[W.MUTE_VIDEO=32773]="MUTE_VIDEO",W[W.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",W[W.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",W[W.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",W[W.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",W[W.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",W[W.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",W[W.SWITCH_CAMERA=32780]="SWITCH_CAMERA",W[W.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",W[W.REPLACE_VIDEO=32782]="REPLACE_VIDEO",W[W.REPLACE_AUDIO=32783]="REPLACE_AUDIO",W[W.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",W[W.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",W[W.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",W[W.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",W[W.JOIN=32788]="JOIN",W[W.LEAVE=32789]="LEAVE",W[W.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",W[W.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",W[W.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",W[W.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",W[W.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",W[W.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",W[W.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",W[W.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",W[W.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",W[W.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",W[W.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",W[W.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",W[W.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",W[W.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",W[W.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",W[W.PUBLISH_AUX=32805]="PUBLISH_AUX",W[W.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",W[W.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",W[W.VIDEO_ENCODER=4004]="VIDEO_ENCODER",W[W.VIDEO_DECODER=4005]="VIDEO_DECODER",W))(Nn||{}),Hl=(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))(Hl||{}),Xm=(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))(Xm||{}),ld=(e=>(e.user="user",e.environment="environment",e))(ld||{}),ud=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(ud||{}),Gl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Gl||{}),Wl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(Wl||{}),Qm=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(Qm||{}),ai=1e8,Pl=class{constructor(){c(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Jr=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Jr||{}),qr=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(qr||{}),hd=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(hd||{}),zl=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(zl||{}),Ym=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(Ym||{}),jl=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.FAILED=1]="FAILED",m[m.WEBCODEC_INIT=2]="WEBCODEC_INIT",m[m.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",m[m.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",m[m.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",m[m.WASM_INIT=6]="WASM_INIT",m[m.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",m[m.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",m[m.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",m[m.TEST=10]="TEST",m[m.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",m))(jl||{}),fo=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(fo||{}),$i=(o=>(o.INTERVAL="interval",o.TIMEOUT="timeout",o.RAF="raf",o.RIC="ric",o.INTERVAL_IN_WORKER="intervalInWorker",o))($i||{});var me={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"},Tt={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: ${lt(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: ${lt(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:s,rule:i,fnName:e,value:t}){return`the min value of ${s||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:s,rule:i,fnName:e,value:t}){return`the max value of ${s||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(s){return`${s.commandDesc||s.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(s){return`SignalChannel setup failure: (errorCode: ${s.errorCode}, errorMsg: ${s.errorMsg} }).`},ERROR_MESSAGE(s){let i=`${s.type} failed`;return s.message&&(i=`${i}: ${s.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(s){return`exchange sdp failed ${s.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(s){return`'${s}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(s){return`'${s}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:s,code:i}){return`Failed to join room - ${s} code: ${i}`},REJOIN_ROOM_FAILED(s){return`reJoin room: ${s.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(s){return`duplicate ${s} stream publishing, please unpublish your prev ${s} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:s,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${s}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(s){return`switchRole failed, errCode: ${s.code} errMsg: ${s.message}.`},CLIENT_BANNED(s){return`client was banned because of ${s.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(s){return`startPublishCDNStream failed, errMsg: ${s.message}.`},STOP_PUBLISH_CDN_FAILED(s){return`stopPublishCDNStream failed, errMsg: ${s.message}.`},INVALID_STREAM_ID(s){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(s){return`cannot replace ${s.kind} track because stream has not ${s.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(s){return`startMixTranscode failed, errMsg: ${s.message}.`},STOP_MIX_TRANSCODE_FAILED(s){return`stopMixTranscode failed, errMsg: ${s.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(s){return`'${s}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:s,fnName:i})=>`'${s}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:s,fnName:i,type:e})=>`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:s=>`${s.media} play failed, browser exception: ${s.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(s){return`${s}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(s){return`${s.signalResponse} failed, response code is ${s.code} , errMsg: ${s.message}.`},CATCH_HANDLER_ERROR({name:s,event:i}){return`an error was caught in ${s}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:s}){return`experimental api ${s} does not exist.`},REPEAT_JOIN:s=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:s}){return`failed to call ${s}() because client was destroyed.`},SEI_NOT_SUPPORT:s=>`not support to sendSEIMessage${s===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:s,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${s?"size":"times"} is over ${s?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(s){return`connection aborted due to: ${s}`},API_CALL_ABORTED(s){let i;return s.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${s.userId} ${s.streamType} stream aborted, reason: remote user ${s.userId} unpublished stream.`:i=`API aborted, reason: ${s.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:s=>`'streamType' is required when 'userId' is not '*', calling ${s}()`};var Zm=(s,i)=>i?`${wi}/${s}/${i}`:`${wi}/${s}/index.html`;var Wg=()=>{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(tl);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 pe(s){let{key:i,data:e,link:t,addDocLink:r=!0}=s,o="",n="",a="";Fe(Tt[i])?o=Tt[i](e):Oe(Tt[i])&&(o=Tt[i]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:l}=Wg();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(Fe(l[i])?a=l[i](e):Oe(l[i])&&(a=l[i]));let h=o;return mi()&&(d&&d[i]&&(Fe(d[i])?n=d[i](e):Oe(d[i])&&(n=d[i])),n&&(r?h=`${n}
8
+ \u8BF7\u67E5\u770B\u6587\u6863: ${Zm("zh-cn",a)}
8
9
 
9
- `:u=`${n}
10
+ `:h=`${n}
10
11
 
11
- `,u+=o)),r&&(u+=`
12
- Refer to: ${ym("en",a)}
13
- `),u}var wd=Be(Lm(),1);var S_=1,I_=0,oa=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",C.createLogger({id:"kv"}));i&&(E.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?501700:511700,cost:t})}),E.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?501700:511700,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:On(this.version||ke),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,max:o=5e3}){var c;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;e>o&&(e=o),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(i))||new Map,a=0;if(J(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:S_,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(J(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:I_,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},na=(U=>(U[U.enterRoom=500700]="enterRoom",U[U.exitRoom=500701]="exitRoom",U[U.switchRole=500702]="switchRole",U[U.destroy=500703]="destroy",U[U.startLocalAudio=500704]="startLocalAudio",U[U.updateLocalAudio=500705]="updateLocalAudio",U[U.stopLocalAudio=500706]="stopLocalAudio",U[U.startLocalVideo=500707]="startLocalVideo",U[U.updateLocalVideo=500708]="updateLocalVideo",U[U.stopLocalVideo=500709]="stopLocalVideo",U[U.startScreenShare=500710]="startScreenShare",U[U.updateScreenShare=500711]="updateScreenShare",U[U.stopScreenShare=500712]="stopScreenShare",U[U.startRemoteVideo=500713]="startRemoteVideo",U[U.updateRemoteVideo=500714]="updateRemoteVideo",U[U.stopRemoteVideo=500715]="stopRemoteVideo",U[U.muteRemoteAudio=500716]="muteRemoteAudio",U[U.setRemoteAudioVolume=500717]="setRemoteAudioVolume",U[U.use=500718]="use",U[U.sendSEIMessage=5e5]="sendSEIMessage",U[U.sendCustomMessage=500001]="sendCustomMessage",U))(na||{}),Md=(u=>(u[u.AudioMixer=550700]="AudioMixer",u[u.AIDenoiser=551700]="AIDenoiser",u[u.VirtualBackground=570700]="VirtualBackground",u[u.Beauty=571700]="Beauty",u[u.Watermark=572700]="Watermark",u[u.BasicBeauty=574700]="BasicBeauty",u[u.CDNStreaming=590700]="CDNStreaming",u[u.DeviceDetector=591700]="DeviceDetector",u[u.Debug=592700]="Debug",u[u.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",u))(Md||{}),Ld=(u=>(u[u.AudioMixer=550701]="AudioMixer",u[u.AIDenoiser=551701]="AIDenoiser",u[u.VirtualBackground=570701]="VirtualBackground",u[u.Beauty=571701]="Beauty",u[u.Watermark=572701]="Watermark",u[u.BasicBeauty=574701]="BasicBeauty",u[u.CDNStreaming=590701]="CDNStreaming",u[u.DeviceDetector=591701]="DeviceDetector",u[u.Debug=592701]="Debug",u[u.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",u))(Ld||{}),Pd=(u=>(u[u.AudioMixer=550702]="AudioMixer",u[u.AIDenoiser=551702]="AIDenoiser",u[u.VirtualBackground=570702]="VirtualBackground",u[u.Beauty=571702]="Beauty",u[u.Watermark=572702]="Watermark",u[u.BasicBeauty=574702]="BasicBeauty",u[u.CDNStreaming=590702]="CDNStreaming",u[u.DeviceDetector=591702]="DeviceDetector",u[u.Debug=592702]="Debug",u[u.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",u))(Pd||{});var A_=new oa(!0),br=new oa(!1);var b=A_;var se={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},C_=new Map([[ae,["Firefox",wn]],[cs,["Edg",Un]],[ps,["Chrome",Yn]],[Le,["Safari",Ri]],[kt,["TBS",Fn]],[ds,["XWEB",$n]],[ls&&Yi,["WeChat",Hn]],[lo,["QQ(Win)",Gn]],[ms,["QQ(Mobile)",os]],[us,["QQ(Mobile X5)",os]],[uo,["QQ(Mac)",Wn]],[mo,["QQ(iPad)",Jn]],[po,["MI",jn]],[fo,["HW",qn]],[_o,["Samsung",Xn]],[go,["OPPO",zn]],[To,["VIVO",Qn]],[as,["EDGE",xn]],[ao,["SogouMobile",Vn]],[co,["Sogou",Bn]]]);function R_(){let s=C_.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var Ud=function(){return!(od||as||cs&&rd<80||ae&&no<56)},wm=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},ca=function(){if(!navigator.mediaDevices)return Di()||C.error(we.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},Pm=!1;function Di(){return location.protocol==="http:"&&!Lt?(Pm||C.error(P({key:L.NOT_SUPPORTED_HTTP})),Pm=!0,!0):!1}var vo=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},xd=function(){return p(this,null,function*(){if(se.detail.isH264EncodeSupported&&se.detail.isVp8EncodeSupported)return{isH264EncodeSupported:se.detail.isH264EncodeSupported,isVp8EncodeSupported:se.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(),se.detail.isH264EncodeSupported=i,se.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:se.detail.isH264EncodeSupported,isVp8EncodeSupported:se.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},da=function(){return p(this,null,function*(){if(se.detail.isH264DecodeSupported&&se.detail.isVp8DecodeSupported)return{isH264DecodeSupported:se.detail.isH264DecodeSupported,isVp8DecodeSupported:se.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}}})},la=kn(()=>p(void 0,null,function*(){if(se.result&&se.detail.isH264EncodeSupported&&se.detail.isVp8EncodeSupported&&se.detail.isH264DecodeSupported&&se.detail.isVp8DecodeSupported)return se;let s=Date.now(),i=Ud(),e=$d(),t=wm(),r=ca(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield xd(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield da();if(!o||!n){let l=yield xd();C.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&pe&&Ye&&!ds&&!kt){let{encode:l,decode:u}=yield b_();o=l,a=u}return se.result=i&&e&&r&&(o||n)&&(a||c),se.detail.isBrowserSupported=i,se.detail.isWebRTCSupported=e,se.detail.isWebCodecsSupported=t,se.detail.isMediaDevicesSupported=r,se.detail.isScreenShareSupported=No(),se.detail.isSmallStreamSupported=ua(),se.detail.isH264EncodeSupported=o,se.detail.isVp8EncodeSupported=n,se.detail.isH264DecodeSupported=a,se.detail.isVp8DecodeSupported=c,se.result||C.error(`${navigator.userAgent} ${Dn(se.detail,!1)}`),M_(),b.addNumber({key:523800,value:Date.now()-s}),se})),y_=function(){return se.result},No=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},aa=null;function b_(){return p(this,null,function*(){return aa||(aa=new Promise(s=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),l.close(),u.close(),c.getTracks().forEach(_=>_.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",_=>u.addIceCandidate(_.candidate)),u.addEventListener("icecandidate",_=>l.addIceCandidate(_.candidate)),l.addTrack(c.getVideoTracks()[0],c);let m=yield l.createOffer();yield l.setLocalDescription(m),yield u.setRemoteDescription(m);let f=yield u.createAnswer(),g=wd.default.parse(f.sdp),D=g.media[0].rtp.findIndex(_=>_.codec==="H264");g.media[0].rtp=[g.media[0].rtp[D]],g.media[0].fmtp=g.media[0].fmtp.filter(_=>_.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(_=>_.payload===g.media[0].rtp[0].payload)),f.sdp=wd.default.write(g),yield u.setLocalDescription(f),yield l.setRemoteDescription(f),n=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let[_,A]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||_.forEach(O=>{O.type==="outbound-rtp"&&O.mediaType===h.VIDEO&&O.bytesSent>0&&(i.encode=!0)}),i.decode||A.forEach(O=>{O.type==="inbound-rtp"&&O.mediaType===h.VIDEO&&O.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),C.warn("detectH264Supported failed",t),s({encode:!0,decode:!0})}})).then(s=>(s.encode||(s.decode=!0),(!s.encode||!s.decode)&&C.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${Dt}`),s)),aa)})}var v_=(s,i,e)=>{location.protocol==="http:"&&!Lt&&(s[i]=()=>{throw new y({code:S.INVALID_OPERATION,message:we.NOT_SUPPORTED_HTTP})})},tr=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(he(s.selected)&&!s.selected):!1};function xm(){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 Um(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Vm(){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 Bm(){return"captureStream"in HTMLCanvasElement.prototype}function ua(){return ls||Ie||dt&&dt<63?!1:!!(Ud()&&Bm())}var N_=function(){if(T(window.RTCRtpTransceiver)||!mt()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:zi}),s.addTransceiver(h.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function vr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function ir(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Kt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function mt(){return lt===11&&!hd?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Es=!(!mt()||Ye&&dt<86);function D_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Do="RTCRtpSender"in window;function Vd(){return Do&&"replaceTrack"in window.RTCRtpSender.prototype}function Oo(){return Do&&"setParameters"in window.RTCRtpSender.prototype&&ir()}var Bd="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,ei=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Fd=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Oi=Do&&"createEncodedStreams"in window.RTCRtpSender.prototype&&hs()>=86,Ss="RTCRtpScriptTransform"in window,ko=Do&&(Oi||Ss),$d=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Fm(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(s.AudioDecoder=!0),T(window.AudioEncoder)||(s.AudioEncoder=!0),T(window.VideoDecoder)||(s.VideoDecoder=!0),T(window.VideoEncoder)||(s.VideoEncoder=!0),T(window.ImageDecoder)||(s.ImageDecoder=!0),s}function $m(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function Hm(){return!T(window.WebTransport)}function O_(){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 k_(){let s={browser:`${qt.name}/${qt.version}`,os:Zn(),displayResolution:xm(),isScreenShareSupported:No(),isWebRTCSupported:$d(),isGetUserMediaSupported:Um(),isWebAudioSupported:Vm(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Fm(),isMediaSessionSupported:$m(),isWebTransportSupported:Hm()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var Gm="checkResult";function M_(){_s.setItem(Gm,{ua:navigator.userAgent,checkResult:se})}function Hd(){Di();let s=_s.getItem(Gm);s&&s.ua===navigator.userAgent&&(se=s.checkResult),la()}function Nr(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var ma="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Jm=Be(Qe(),1);var Wm=Symbol("instance"),WS=Symbol("abortCtrl"),ha=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,wo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Lo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function L_(s){return typeof s=="object"&&s&&"then"in s}var Po=new Map;function _e(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let c=Po.get(t)||[];Po.has(t)||Po.set(t,c),c.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...c){let l=this;if(e.context&&(l=$.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[ha]:Promise.resolve(l[ha]);l.state instanceof Mo&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(s)?s.length==0?l.state instanceof Mo&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(u=new Lo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(u=new Lo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let m=A=>{if(e.fail&&e.fail.call(this,A),e.sync){if(e.ignoreError)return A;throw A}else return e.ignoreError?Promise.resolve(A):Promise.reject(A)};if(u)return m(u);let f=l.state,g=new Mo(f,i,n);wo.call(l,g);let D=A=>{var O;return l[ha]=A,g.aborted||(wo.call(l,i),(O=e.success)===null||O===void 0||O.call(this,l[ha])),A},_=A=>(wo.call(l,f,A),m(A));try{let A=a.apply(this,c);return L_(A)?A.then(D).catch(_):e.sync?D(A):Promise.resolve(D(A))}catch(A){return _(new Lo(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${A}`,A instanceof Error?A:new Error(String(A))))}}}}var P_=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 wo(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit($.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var $=class s extends Jm.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=s.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Wm];r?this.name=r.name+"-"+r.count++:t[Wm]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Po.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Po.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:m})=>{typeof l=="string"?r.push({from:l,to:u,action:m}):l.length?l.forEach(f=>{r.push({from:f,to:u,action:m})}):o.push({to:u,action:m})}),r.forEach(({from:l,to:u,action:m})=>{n.add(l),n.add(u),n.add(m+"ing"),t.add(`${l} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${u} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${l} : ${m} \u{1F534}`)}),o.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(m=>{m!==l&&t.add(`${m} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=s.instances.get(i),e||s.instances.set(i,e=new s(i,void 0,Object.create(s.prototype)))):(e=s.instances2.get(i),e||s.instances2.set(i,e=new s(i.constructor.name,void 0,Object.create(s.prototype)))),e}static getState(i){var e;return(e=s.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){P_(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){wo.call(this,i)}};$.STATECHANGED="stateChanged";$.UPDATEAFSM="updateAFSM";$.INIT="[*]";$.ON="on";$.OFF="off";$.instances=new Map;$.instances2=new WeakMap;var Wd=typeof window!="undefined",jm=Wd&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},w_=Wd&&window.cancelIdleCallback||function(s){clearTimeout(s)},qm=Wd&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),De=class De{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=v({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=v({delay:1e4,count:0},t):i==="raf"?t=v({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=v({delay:2e3,count:0,backgroundTask:!0},t);let r=w(v({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,De.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){De.sharedWorker||(De.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
12
+ `,h+=o)),r&&(h+=`
13
+ Refer to: ${Zm("en",a)}
14
+ `),h}var Zl=gt(np(),1);var eE=1,tE=0,pd=class{constructor(i=!0){c(this,"countMap",new Map);c(this,"distributionMap",new Map);c(this,"version");c(this,"log",z.createLogger({id:"kv"}));i&&(x.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===S.AUDIO?501700:511700,cost:t})}),x.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===S.AUDIO?501700:511700,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Ba(this.version||Rt),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(De(t))n=Math.floor(e/t);else for(let d=t.length-1;d>0;d--)if(e>t[d]){n=d;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:eE,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=H.UNKNOWN;e&&(De(e)?t=e:(!M(e.extraCode)||!M(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:tE,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},fd=(N=>(N[N.enterRoom=500700]="enterRoom",N[N.exitRoom=500701]="exitRoom",N[N.switchRole=500702]="switchRole",N[N.destroy=500703]="destroy",N[N.startLocalAudio=500704]="startLocalAudio",N[N.updateLocalAudio=500705]="updateLocalAudio",N[N.stopLocalAudio=500706]="stopLocalAudio",N[N.startLocalVideo=500707]="startLocalVideo",N[N.updateLocalVideo=500708]="updateLocalVideo",N[N.stopLocalVideo=500709]="stopLocalVideo",N[N.startScreenShare=500710]="startScreenShare",N[N.updateScreenShare=500711]="updateScreenShare",N[N.stopScreenShare=500712]="stopScreenShare",N[N.startRemoteVideo=500713]="startRemoteVideo",N[N.updateRemoteVideo=500714]="updateRemoteVideo",N[N.stopRemoteVideo=500715]="stopRemoteVideo",N[N.muteRemoteAudio=500716]="muteRemoteAudio",N[N.setRemoteAudioVolume=500717]="setRemoteAudioVolume",N[N.use=500718]="use",N[N.sendSEIMessage=5e5]="sendSEIMessage",N[N.sendCustomMessage=500001]="sendCustomMessage",N))(fd||{}),Xl=(h=>(h[h.AudioMixer=550700]="AudioMixer",h[h.AIDenoiser=551700]="AIDenoiser",h[h.VirtualBackground=570700]="VirtualBackground",h[h.Beauty=571700]="Beauty",h[h.Watermark=572700]="Watermark",h[h.BasicBeauty=574700]="BasicBeauty",h[h.CDNStreaming=590700]="CDNStreaming",h[h.DeviceDetector=591700]="DeviceDetector",h[h.Debug=592700]="Debug",h[h.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",h))(Xl||{}),Ql=(h=>(h[h.AudioMixer=550701]="AudioMixer",h[h.AIDenoiser=551701]="AIDenoiser",h[h.VirtualBackground=570701]="VirtualBackground",h[h.Beauty=571701]="Beauty",h[h.Watermark=572701]="Watermark",h[h.BasicBeauty=574701]="BasicBeauty",h[h.CDNStreaming=590701]="CDNStreaming",h[h.DeviceDetector=591701]="DeviceDetector",h[h.Debug=592701]="Debug",h[h.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",h))(Ql||{}),Yl=(h=>(h[h.AudioMixer=550702]="AudioMixer",h[h.AIDenoiser=551702]="AIDenoiser",h[h.VirtualBackground=570702]="VirtualBackground",h[h.Beauty=571702]="Beauty",h[h.Watermark=572702]="Watermark",h[h.BasicBeauty=574702]="BasicBeauty",h[h.CDNStreaming=590702]="CDNStreaming",h[h.DeviceDetector=591702]="DeviceDetector",h[h.Debug=592702]="Debug",h[h.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",h))(Yl||{});var iE=new pd(!0),Cs=new pd(!1);var Q=iE;var xe={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},rE=new Map([[Ue,["Firefox",Wa]],[oo,["Edg",ja]],[ho,["Chrome",nd]],[pt,["Safari",fr]],[gi,["TBS",Xa]],[no,["XWEB",Qa]],[ao&&zr,["WeChat",Ya]],[fn,["QQ(Win)",Za]],[lo,["QQ(Mobile)",io]],[co,["QQ(Mobile X5)",io]],[_n,["QQ(Mac)",Ka]],[gn,["QQ(iPad)",ed]],[Tn,["MI",td]],[Sn,["HW",id]],[In,["Samsung",rd]],[An,["OPPO",sd]],[Cn,["VIVO",od]],[so,["EDGE",za]],[mn,["SogouMobile",Ja]],[pn,["Sogou",qa]]]);function sE(){let s=rE.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var eu=function(){return!(Al||so||oo&&Sl<80||Ue&&hn<56)},dp=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},gd=function(){if(!navigator.mediaDevices)return Ir()||z.error(Tt.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},ap=!1;function Ir(){return location.protocol==="http:"&&!Ti?(ap||z.error(pe({key:me.NOT_SUPPORTED_HTTP})),ap=!0,!0):!1}var tu=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Kl=function(){return A(this,null,function*(){if(xe.detail.isH264EncodeSupported&&xe.detail.isVp8EncodeSupported)return{isH264EncodeSupported:xe.detail.isH264EncodeSupported,isVp8EncodeSupported:xe.detail.isVp8EncodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection,r=document.createElement(S.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(),xe.detail.isH264EncodeSupported=i,xe.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:xe.detail.isH264EncodeSupported,isVp8EncodeSupported:xe.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Ed=function(){return A(this,null,function*(){if(xe.detail.isH264DecodeSupported&&xe.detail.isVp8DecodeSupported)return{isH264DecodeSupported:xe.detail.isH264DecodeSupported,isVp8DecodeSupported:xe.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}}})},Td=$a(()=>A(void 0,null,function*(){if(xe.result&&xe.detail.isH264EncodeSupported&&xe.detail.isVp8EncodeSupported&&xe.detail.isH264DecodeSupported&&xe.detail.isVp8DecodeSupported)return xe;let s=Date.now(),i=eu(),e=ou(),t=dp(),r=gd(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield Kl(),{isH264DecodeSupported:a,isVp8DecodeSupported:d}=yield Ed();if(!o||!n){let l=yield Kl();z.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&ze&&xt&&!no&&!gi){let{encode:l,decode:h}=yield nE();o=l,a=h}return xe.result=i&&e&&r&&(o||n)&&(a||d),xe.detail.isBrowserSupported=i,xe.detail.isWebRTCSupported=e,xe.detail.isWebCodecsSupported=t,xe.detail.isMediaDevicesSupported=r,xe.detail.isScreenShareSupported=kn(),xe.detail.isSmallStreamSupported=On(),xe.detail.isH264EncodeSupported=o,xe.detail.isVp8EncodeSupported=n,xe.detail.isH264DecodeSupported=a,xe.detail.isVp8DecodeSupported=d,xe.result||z.error(`${navigator.userAgent} ${Ua(xe.detail,!1)}`),hE(),Q.addNumber({key:523800,value:Date.now()-s}),xe})),oE=function(){return xe.result},kn=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},_d=null;function nE(){return A(this,null,function*(){return _d||(_d=new Promise(s=>A(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),l.close(),h.close(),d.getTracks().forEach(f=>f.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let d=t.captureStream(),l=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",f=>h.addIceCandidate(f.candidate)),h.addEventListener("icecandidate",f=>l.addIceCandidate(f.candidate)),l.addTrack(d.getVideoTracks()[0],d);let u=yield l.createOffer();yield l.setLocalDescription(u),yield h.setRemoteDescription(u);let m=yield h.createAnswer(),p=Zl.default.parse(m.sdp),g=p.media[0].rtp.findIndex(f=>f.codec==="H264");p.media[0].rtp=[p.media[0].rtp[g]],p.media[0].fmtp=p.media[0].fmtp.filter(f=>f.payload===p.media[0].rtp[0].payload),p.media[0].rtcpFb&&(p.media[0].rtcpFb=p.media[0].rtcpFb.filter(f=>f.payload===p.media[0].rtp[0].payload)),m.sdp=Zl.default.write(p),yield h.setLocalDescription(m),yield l.setRemoteDescription(m),n=setInterval(()=>A(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let[f,T]=yield Promise.all([l.getSenders()[0].getStats(),h.getReceivers()[0].getStats()]);i.encode||f.forEach(I=>{I.type==="outbound-rtp"&&I.mediaType===S.VIDEO&&I.bytesSent>0&&(i.encode=!0)}),i.decode||T.forEach(I=>{I.type==="inbound-rtp"&&I.mediaType===S.VIDEO&&I.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),z.warn("detectH264Supported failed",t),s({encode:!0,decode:!0})}})).then(s=>(s.encode||(s.decode=!0),(!s.encode||!s.decode)&&z.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${fi}`),s)),_d)})}var aE=(s,i,e)=>{location.protocol==="http:"&&!Ti&&(s[i]=()=>{throw new X({code:H.INVALID_OPERATION,message:Tt.NOT_SUPPORTED_HTTP})})},Xr=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(Qe(s.selected)&&!s.selected):!1};function cp(){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 lp(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function up(){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 hp(){return"captureStream"in HTMLCanvasElement.prototype}function On(){return ao||Ye||qt&&qt<63?!1:!!(eu()&&hp())}var dE=function(){if(M(window.RTCRtpTransceiver)||!Yt()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:Gr}),s.addTransceiver(S.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function Rs(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Qr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Hi(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Yt(){return Xt===11&&!kl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var go=!(!Yt()||xt&&qt<86);function cE(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var wn="RTCRtpSender"in window;function iu(){return wn&&"replaceTrack"in window.RTCRtpSender.prototype}function Mn(){return wn&&"setParameters"in window.RTCRtpSender.prototype&&Qr()}var ru="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Gi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,su=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ar=wn&&"createEncodedStreams"in window.RTCRtpSender.prototype&&uo()>=86,Sd="RTCRtpScriptTransform"in window,xn=wn&&(Ar||Sd),ou=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function mp(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return M(window.AudioDecoder)||(s.AudioDecoder=!0),M(window.AudioEncoder)||(s.AudioEncoder=!0),M(window.VideoDecoder)||(s.VideoDecoder=!0),M(window.VideoEncoder)||(s.VideoEncoder=!0),M(window.ImageDecoder)||(s.ImageDecoder=!0),s}function pp(){return"mediaSession"in navigator&&!M(navigator.mediaSession.setActionHandler)}function fp(){return!M(window.WebTransport)}function lE(){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 uE(){let s={browser:`${Vi.name}/${Vi.version}`,os:ad(),displayResolution:cp(),isScreenShareSupported:kn(),isWebRTCSupported:ou(),isGetUserMediaSupported:lp(),isWebAudioSupported:up(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:mp(),isMediaSessionSupported:pp(),isWebTransportSupported:fp()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var _p="checkResult";function hE(){po.setItem(_p,{ua:navigator.userAgent,checkResult:xe})}function nu(){Ir();let s=po.getItem(_p);s&&s.ua===navigator.userAgent&&(xe=s.checkResult),Td()}function ys(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Id="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Ep=gt(Mt(),1);var gp=Symbol("instance"),yA=Symbol("abortCtrl"),Ad=Symbol("cacheResult"),Ln=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Vn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Pn=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function mE(s){return typeof s=="object"&&s&&"then"in s}var Un=new Map;function qe(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let d=Un.get(t)||[];Un.has(t)||Un.set(t,d),d.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...d){let l=this;if(e.context&&(l=ge.get(typeof e.context=="function"?e.context.call(this,...d):e.context)),l.state===i)return e.sync?l[Ad]:Promise.resolve(l[Ad]);l.state instanceof Ln&&l.state.action==e.abortAction&&l.state.abort(l);let h=null;Array.isArray(s)?s.length==0?l.state instanceof Ln&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(h=new Pn(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(h=new Pn(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let u=T=>{if(e.fail&&e.fail.call(this,T),e.sync){if(e.ignoreError)return T;throw T}else return e.ignoreError?Promise.resolve(T):Promise.reject(T)};if(h)return u(h);let m=l.state,p=new Ln(m,i,n);Vn.call(l,p);let g=T=>{var I;return l[Ad]=T,p.aborted||(Vn.call(l,i),(I=e.success)===null||I===void 0||I.call(this,l[Ad])),T},f=T=>(Vn.call(l,m,T),u(T));try{let T=a.apply(this,d);return mE(T)?T.then(g).catch(f):e.sync?g(T):Promise.resolve(g(T))}catch(T){return f(new Pn(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${T}`,T instanceof Error?T:new Error(String(T))))}}}}var pE=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 Vn(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(ge.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var ge=class s extends Ep.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=s.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[gp];r?this.name=r.name+"-"+r.count++:t[gp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Un.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Un.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:h,action:u})=>{typeof l=="string"?r.push({from:l,to:h,action:u}):l.length?l.forEach(m=>{r.push({from:m,to:h,action:u})}):o.push({to:h,action:u})}),r.forEach(({from:l,to:h,action:u})=>{n.add(l),n.add(h),n.add(u+"ing"),t.add(`${l} --> ${u}ing : ${u}`),t.add(`${u}ing --> ${h} : ${u} \u{1F7E2}`),t.add(`${u}ing --> ${l} : ${u} \u{1F534}`)}),o.forEach(({to:l,action:h})=>{t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.forEach(u=>{u!==l&&t.add(`${u} --> ${h}ing : ${h}`)})});let d=[...t];return Object.defineProperties(i,{stateDiagram:{value:d},allStates:{value:n}}),d}static get(i){let e;return typeof i=="string"?(e=s.instances.get(i),e||s.instances.set(i,e=new s(i,void 0,Object.create(s.prototype)))):(e=s.instances2.get(i),e||s.instances2.set(i,e=new s(i.constructor.name,void 0,Object.create(s.prototype)))),e}static getState(i){var e;return(e=s.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){pE(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Vn.call(this,i)}};ge.STATECHANGED="stateChanged";ge.UPDATEAFSM="updateAFSM";ge.INIT="[*]";ge.ON="on";ge.OFF="off";ge.instances=new Map;ge.instances2=new WeakMap;var du=typeof window!="undefined",Tp=du&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},fE=du&&window.cancelIdleCallback||function(s){clearTimeout(s)},Sp=du&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),ht=class ht{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=Z({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=Z({delay:1e4,count:0},t):i==="raf"?t=Z({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=Z({delay:2e3,count:0,backgroundTask:!0},t);let r=de(Z({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,ht.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){ht.sharedWorker||(ht.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
14
15
  const timers = new Map();
15
16
  self.onmessage = function(e) {
16
17
  const { taskId, delay, type } = e.data;
@@ -23,14 +24,14 @@ Refer to: ${ym("en",a)}
23
24
  timers.delete(taskId);
24
25
  }
25
26
  };
26
- `],{type:"application/javascript"}))),De.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=De.workerTasks.get(e.data.taskId);r&&(De.isBreakLoop(r)?((t=De.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),De.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),De.workerTasks.set(i.taskID,i),De.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!De.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=x(),t,r=()=>{if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!De.isBreakLoop(i))return i.ricID=jm(r,{timeout:i.delay})};return i.ricID=jm(r,{timeout:i.delay})}static raf(i){let e=x(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=x()-e,e=x(),i.callback(),i.loopCount+=1,De.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!De.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=x()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&qm&&qm(r),o&&w_(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(De,"taskMap",new Map),d(De,"currentTaskID",1),d(De,"sharedWorker",null),d(De,"workerTasks",new Map);var Gd=De,oe=Gd;var eI={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 ue={LOADED_DATA:h.LOADEDDATA,LOADED_META_DATA:h.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var ii={};fi(ii,{create:()=>Ge,remove:()=>ve});var xo=new WeakMap;function Ge(s,i){xo.has(s)||xo.set(s,[]);let e=xo.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 ve(s){let i=xo.get(s);i&&(i.forEach(e=>e()),xo.delete(s))}var Jd=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:ke,env:_i.QCLOUD,browserVersion:qt.name+qt.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){Lt||!C.isAbleToUpload||this._configs.env===_i.QCLOUD&&this.uploadEventToKibana(w(v({},i),{result:"success"}))}logFailedEvent(i){if(Lt||!C.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||S.UNKNOWN};this._configs.env===_i.QCLOUD&&this.uploadEventToKibana(w(v({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:_n(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:ke,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
27
- ${t.stack}`)),this.sendRequest(Ei(this._configs.sdkAppId,Ji.LOG),r)}sendRequest(i,e){setTimeout(()=>Ai({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},ie=new Jd;var ri=new WeakMap;function ht({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=jt({retryFunction:n.value,settings:s,onError({error:c,retry:l,reject:u,retryFuncArgs:m}){var f;i?i.call(this,c,()=>{var g;(g=ri.get(r))!=null&&g.has(o)?l():u(c)},u,m):(f=ri.get(r))!=null&&f.has(o)?l():u(c)},onRetrying(c,l){var u;Jt(e)&&e.call(this,c,l),(u=ri.get(r))!=null&&u.has(o)&&(ri.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=ri.get(r);return l?l.set(o,{args:c}):ri.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=ri.get(r))==null?void 0:u.delete(o)})},n}}function Uo({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,l;if((c=ri.get(t))!=null&&c.has(s)){let{stopRetry:u,args:m}=ri.get(t).get(s),f=!0;if(e){for(let g of m)if(!a.find(D=>D===g)){f=!1;break}}f&&(i&&i.apply(this,a),u&&u(),(l=ri.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var si=class extends ${constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=pr,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return p(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=P({key:L.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new y({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Zi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():ud?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Ge(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e).add(h.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);ii==null||ii.create(e,e).add(h.ENDED,t).add(h.MUTE,t).add(h.UNMUTE,t),e.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),e.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){E.on(I.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ve(e)}unbindEvents(){this.element&&ve(this.element),this.unbindTrackEvents(),E.off(I.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&&(oe.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),Ie&&(this._interval=oe.run("timeout",()=>{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}`),ie.uploadEvent({log:`stat-${this.kind}-${rt.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),ad||nd?this.emit(ue.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(ue.LOADED_DATA);break;case h.LOADEDMETADATA:this.kind===h.VIDEO&&this.emit(ue.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ie.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),b.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),ie.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),b.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ue.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ii(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ii(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.handleStopped(h.ENDED);break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired?this.handlePlaying(h.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};N([ht({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],si.prototype,"doReplayByRecreateMediaStream",1),N([_e([],"PLAYING",{sync:!0})],si.prototype,"handlePlaying",1),N([_e("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],si.prototype,"handlePaused",1),N([_e([],"STOPPED",{sync:!0})],si.prototype,"handleStopped",1);var ki="trtc_autoplay",jd=`${ki}_mask`,Is=`${ki}_wrapper`,Xm=`${ki}_header`,qd=`${ki}_content`,pa=`${ki}_action_wrapper`,Xd=`${ki}_question`,zd=`${ki}_collapse`,fa=`${ki}_action_confirm`,zm=`${ki}_detail`,Qm="#2473E8",Yd="dialog",U_=`${Yd}-show`,V_=`${Yd}-1`,B_=`${Yd}-2`,Ym=!1,Zd=()=>!!document.querySelector(`.${Is}`),Km=`${Ht}/${vt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Zm=`<br><a href='${Km}' target='_blank'>${vt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,F_=`${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${Zm}`:`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. ${Zm}`}`,Qd=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(vt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ym){let i=document.createElement("style");i.innerHTML=`.${jd}{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;}.${jd} div:not(.${pa}){display:block !important;}.${Is}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Is} a{color:${Qm};}.${Xm}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${qd}{margin:8px 0;}.${pa}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${zd}{margin-right:auto;cursor:pointer}.${Xd}{height:100%;line-height:16px;cursor:pointer;}.${fa}{margin-left:8px;color:#fff;background:${Qm};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${fa}:hover{opacity:0.9;}.${zd},.${fa},.${qd},.${Xd}{font-size:14px;}@media screen and (max-width:750px){.${Is}{width:80vw;}}`,document.head.appendChild(i),Ym=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${jd}"><div class='${Is}'><div class='${Xm}'>${location.host}</div><div class='${qd}'>${this.content}</div><div class='${zm}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${F_}</div><div class='${pa}'></div></div></div>`.trim();let e=document.createElement("button");e.className=fa,e.innerText=vt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Xd,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
27
+ `],{type:"application/javascript"}))),ht.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=ht.workerTasks.get(e.data.taskId);r&&(ht.isBreakLoop(r)?((t=ht.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),ht.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),ht.workerTasks.set(i.taskID,i),ht.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!ht.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=le(),t,r=()=>{if(t=le()-e,t>=i.delay&&(e=le()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!ht.isBreakLoop(i))return i.ricID=Tp(r,{timeout:i.delay})};return i.ricID=Tp(r,{timeout:i.delay})}static raf(i){let e=le(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=le()-e,e=le(),i.callback(),i.loopCount+=1,ht.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=le()-e,t>=i.delay&&(e=le()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!ht.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=le()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Sp&&Sp(r),o&&fE(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};c(ht,"taskMap",new Map),c(ht,"currentTaskID",1),c(ht,"sharedWorker",null),c(ht,"workerTasks",new Map);var au=ht,Le=au;var LA={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:S.SEI_MESSAGE,ERROR:"error"};var Ge={LOADED_DATA:S.LOADEDDATA,LOADED_META_DATA:S.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var zi={};nr(zi,{create:()=>vt,remove:()=>at});var Bn=new WeakMap;function vt(s,i){Bn.has(s)||Bn.set(s,[]);let e=Bn.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 at(s){let i=Bn.get(s);i&&(i.forEach(e=>e()),Bn.delete(s))}var cu=class{constructor(){c(this,"_roomIdMap",new Map);c(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Rt,env:ar.QCLOUD,browserVersion:Vi.name+Vi.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){Ti||!z.isAbleToUpload||this._configs.env===ar.QCLOUD&&this.uploadEventToKibana(de(Z({},i),{result:"success"}))}logFailedEvent(i){if(Ti||!z.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)||H.UNKNOWN};this._configs.env===ar.QCLOUD&&this.uploadEventToKibana(de(Z({},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:ya(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Rt,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
28
+ ${t.stack}`)),this.sendRequest(lr(this._configs.sdkAppId,$r.LOG),r)}sendRequest(i,e){setTimeout(()=>mr({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},Me=new cu;var ji=new WeakMap;function Gt({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Ui({retryFunction:n.value,settings:s,onError({error:d,retry:l,reject:h,retryFuncArgs:u}){var m;i?i.call(this,d,()=>{var p;(p=ji.get(r))!=null&&p.has(o)?l():h(d)},h,u):(m=ji.get(r))!=null&&m.has(o)?l():h(d)},onRetrying(d,l){var h;Pi(e)&&e.call(this,d,l),(h=ji.get(r))!=null&&h.has(o)&&(ji.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...d){let l=ji.get(r);return l?l.set(o,{args:d}):ji.set(r,new Map([[o,{args:d}]])),a.apply(this,d).finally(()=>{var h;return(h=ji.get(r))==null?void 0:h.delete(o)})},n}}function $n({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var d,l;if((d=ji.get(t))!=null&&d.has(s)){let{stopRetry:h,args:u}=ji.get(t).get(s),m=!0;if(e){for(let p of u)if(!a.find(g=>g===p)){m=!1;break}}m&&(i&&i.apply(this,a),h&&h(),(l=ji.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var Ji=class extends ge{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;c(this,"id");c(this,"element",null);c(this,"track");c(this,"url");c(this,"attr");c(this,"mode");c(this,"muted");c(this,"_log");c(this,"_pausedRetryCount");c(this,"_isElementPlayingFired",!1);c(this,"_interval");c(this,"_delayDestroyTimeoutId",0);c(this,"_playSuccessResolve");c(this,"_isReplayByRecreateMediaStreamCalled",!1);c(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=ls,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return A(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=pe({key:me.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 X({code:H.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!jr?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(S.ENDED),this._interval>0&&Le.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Nl?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 vt(this.element,this.element).add(S.PLAYING,e).add(S.ENDED,e).add(S.PAUSE,e).add(S.ERROR,e).add(S.LOADEDDATA,e).add(S.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);zi==null||zi.create(e,e).add(S.ENDED,t).add(S.MUTE,t).add(S.UNMUTE,t),e.readyState===S.ENDED&&this.handleTrackEvent({type:S.ENDED}),e.muted&&this.handleTrackEvent({type:S.MUTE})}}bindAutoPlayEvent(){x.on(B.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&at(e)}unbindEvents(){this.element&&at(this.element),this.unbindTrackEvents(),x.off(B.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case S.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(S.PLAYING),this._interval&&(Le.clearTask(this._interval),this._interval=-1);break;case S.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(S.ENDED);break;case S.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(S.PAUSE),Ye&&(this._interval=Le.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case S.ERROR:if(this.element&&this.element.error){this.handlePaused(S.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}`),Me.uploadEvent({log:`stat-${this.kind}-${Ft.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),Rl||Cl?this.emit(Ge.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case S.LOADEDDATA:this.kind===S.VIDEO&&this.emit(Ge.LOADED_DATA);break;case S.LOADEDMETADATA:this.kind===S.VIDEO&&this.emit(Ge.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Me.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Q.addSuccessEvent({key:this.kind===S.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),Me.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Q.addFailedEvent({key:this.kind===S.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(Ge.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{hr(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)}),hr(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case S.ENDED:this.handleStopped(S.ENDED);break;case S.MUTE:this.handlePaused(S.MUTE);break;case S.UNMUTE:this._isElementPlayingFired?this.handlePlaying(S.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(Ge.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Ge.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Ge.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};J([Gt({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],Ji.prototype,"doReplayByRecreateMediaStream",1),J([qe([],"PLAYING",{sync:!0})],Ji.prototype,"handlePlaying",1),J([qe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Ji.prototype,"handlePaused",1),J([qe([],"STOPPED",{sync:!0})],Ji.prototype,"handleStopped",1);var Cr="trtc_autoplay",lu=`${Cr}_mask`,Eo=`${Cr}_wrapper`,Ip=`${Cr}_header`,uu=`${Cr}_content`,Cd=`${Cr}_action_wrapper`,hu=`${Cr}_question`,mu=`${Cr}_collapse`,Rd=`${Cr}_action_confirm`,Ap=`${Cr}_detail`,Cp="#2473E8",fu="dialog",gE=`${fu}-show`,EE=`${fu}-1`,TE=`${fu}-2`,Rp=!1,_u=()=>!!document.querySelector(`.${Eo}`),bp=`${wi}/${mi()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,yp=`<br><a href='${bp}' target='_blank'>${mi()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,SE=`${mi()?`\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${yp}`:`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. ${yp}`}`,pu=class{constructor(){c(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");c(this,"_dialogNode",null);c(this,"_bodyPosition","");c(this,"_showDetail",!1);c(this,"_isCollapseClicked",!1);c(this,"_isQuestionClicked",!1);if(mi()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Rp){let i=document.createElement("style");i.innerHTML=`.${lu}{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;}.${lu} div:not(.${Cd}){display:block !important;}.${Eo}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Eo} a{color:${Cp};}.${Ip}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${uu}{margin:8px 0;}.${Cd}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${mu}{margin-right:auto;cursor:pointer}.${hu}{height:100%;line-height:16px;cursor:pointer;}.${Rd}{margin-left:8px;color:#fff;background:${Cp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Rd}:hover{opacity:0.9;}.${mu},.${Rd},.${uu},.${hu}{font-size:14px;}@media screen and (max-width:750px){.${Eo}{width:80vw;}}`,document.head.appendChild(i),Rp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${lu}"><div class='${Eo}'><div class='${Ip}'>${location.host}</div><div class='${uu}'>${this.content}</div><div class='${Ap}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${SE}</div><div class='${Cd}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Rd,e.innerText=mi()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=hu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
28
29
  <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
29
30
  <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
30
31
  <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
31
32
  <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
32
33
  </svg>
33
- `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=zd,r.innerText=`${vt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${pa}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){Zd()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Is}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),ie.uploadEvent({log:U_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){C.warn("confirm clicked, try resume stream"),E.emit(I.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${zm}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ie.uploadEvent({log:V_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Km,"_blank"),this._isQuestionClicked||ie.uploadEvent({log:B_}),this._isQuestionClicked=!0}},eh=Qd;var pt=class extends si{constructor(e){super(e,h.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===h.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,o;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===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.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=pr,this._log.info(`view container ${(o=this.container)==null?void 0:o.id} is recreated`)),this._pausedRetryCount>0&&!Zd()&&(this._log.info(`[${pr-this._pausedRetryCount+1}/${pr}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((o=this.element)==null||o.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Nr()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function Dr(s,i){return p(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),C.info("worklet addModule success")}catch(e){throw C.info(`worklet addModule catch error. ${e.message}`),e}})}var Vo;typeof AudioContext!="undefined"?Vo=AudioContext:typeof webkitAudioContext!="undefined"?Vo=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Vo=mozAudioContext);var xt,th=-1;ih();function ih(){try{if(xt)return;xt=new Vo({sampleRate:48e3}),xt.onstatechange=()=>{C.info(`context state: ${xt.state}${xt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),As()},clearTimeout(th)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof Vo}`),th=setTimeout(ih,1e3)}}var As=()=>{xt.state==="suspended"?(Cs(),document.addEventListener("click",As)):xt.state==="interrupted"?Cs():(document.removeEventListener("visibilitychange",As),document.removeEventListener("click",As))},Kd=0,el=-1;function Cs(){return new Promise((s,i)=>{if(xt.state==="running")return s();Date.now()-Kd<1e3?(clearTimeout(el),el=setTimeout(()=>{Kd=Date.now(),xt.resume().then(s,i)},1e3)):(clearTimeout(el),Kd=Date.now(),xt.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",As)})}document.addEventListener("click",As);var Re=s=>xt;var We=class{constructor(){d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){C.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),b.addSuccessEvent({key:502701})}catch(r){C.error(r),b.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),b.addSuccessEvent({key:502702})}catch(e){C.error(e),b.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{i._connect(e.node)||e.connectNext(i)})}_connect(i){return!this.node||!i?!1:((this.node2||this.node).connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},_a=class extends We{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Bo=class{constructor(){d(this,"source",new We);d(this,"gain",new We);d(this,"destination",new We)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Re().createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.replaceNode(tl(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}},Rs=class extends Bo{constructor(e){super();this.context=e;d(this,"denoiser",new We);d(this,"voiceChanger",new We);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},ga=class{constructor(){d(this,"audioContext",Re("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},rh=new WeakMap;function tl(s){let i=rh.get(s);if(i)return i;let e=Re();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return rh.set(s,i),i}var ft=class ft{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,E.on(I.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-ft.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!ft.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';ft.workletReady=Dr(ft.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return ft.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ft.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{ft.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ie.logFailedEvent({userId:this._log.userId,eventType:rt.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Re("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{ft.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,E.off(I.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(ft,"lastMessageTime",0),d(ft,"audioContext",Re("volume-meter")),d(ft,"workletReady");var Ta=ft,Ea=class extends We{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new Ta(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},Or=Ta;var ah=Be(Qe(),1);var oh=s=>i=>i.deviceId===s;var Fo=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ys(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(oh(r.deviceId))){let o=`${this.kind}${this.type}Added`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(oh(r.deviceId))){let o=`${this.kind}${this.type}Removed`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},il=class extends ah.EventEmitter{constructor(){super();d(this,"audioInputs",new Fo(h.AUDIO));d(this,"videoInputs",new Fo(h.VIDEO));d(this,"audioOutputs",new Fo(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){Sa().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield Sa(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Me=zs||Xr?null:new il;function ys(s){return s.deviceId===s.groupId&&s.groupId===""}function Sa(){return p(this,arguments,function*(s=0){if(Di()||!ca())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ys(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),e.audio&&Cs()}catch(r){C.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&rl.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function ot(s=!1){return Me.update(s?1:0).then(i=>i.audioInputs.devices)}function _t(s=!1){return Me.update(s?2:0).then(i=>i.videoInputs.devices)}var nh=!1;function ch(){return p(this,null,function*(){try{nh||(nh=!0,C.info(`speakers:${(yield rr()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function rr(s=!1){return p(this,null,function*(){return(Ie||Le)&&(s=!1),Me.update(s?1:0).then(i=>i.audioOutputs.devices)})}var rl=new Set;function dh(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!!rl.has(t)}function lh(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!!rl.has(t)}function sl(s,i){return p(this,null,function*(){let t=(yield ot()).find(r=>r.deviceId===fr);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function uh(o){return p(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===h.AUDIO&&s===fr?yield sl(e,t):!0})}var Ia,ol=class extends Bo{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeDestination");d(this,"analyser",new _a);this.volumeMeter=new Ea({log:this.log}),this.volumeDestination=new We,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Aa=class s extends si{constructor(e){super(e,h.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Re("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new ol(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Xt==="15.2"||Xt==="15.3"||Xt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Ia||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,J(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Ia&&(Ia=void 0),this.bindElementEvents()}play(e){return p(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Re("player").createAnalyser()),ch(),Fe(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Ca=class extends Aa{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Ra=class extends Aa{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new We);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(Re("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):Ie||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ve(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Zi&&(Ia=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var kr=class extends ${constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?Ra:pt}){var a;super();d(this,"id",Io());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=C.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Mi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Mi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{E.emit(I.PLAYER_STATE_CHANGED,v({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),E.emit(I.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||C}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 p(this,null,function*(){let r=Te(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Te(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof pt&&this.player.setContainer(r)),E.emit(I.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Te(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===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&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new pt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Zc(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),E.emit(e?I.TRACK_MUTED:I.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Ge(e,e).add(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){ve(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Zc(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new eh;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof pt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.LOADED_META_DATA&&!r&&!o||(e===ue.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:r,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};N([_e([],$.INIT,{sync:!0})],kr.prototype,"close",1);var $_=Object.prototype.hasOwnProperty,{toString:SC}=Object.prototype;function H_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(He(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if($_.call(s,i))return!1;return!0}}return!1}var oi=H_;var G_=function(s){return p(this,null,function*(){let i=J_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield ot(),C.info(`microphones: ${gt(e.map(o=>w(v({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield _t(),C.info(`cameras: ${gt(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Fd&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${gt(n.getCapabilities(),{keysToInclude:vn})}`)}),i.audio&&Cs(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=P({key:L.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=P({key:L.MICROPHONE_NOT_FOUND}))),new y({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},W_=jt({retryFunction:G_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!Le||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&mh(t[0].microphoneId,!1),t[0].cameraId&&mh(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{ie.logFailedEvent({eventType:rt.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{ie.logSuccessEvent({eventType:rt.GET_USER_MEDIA_RETRY}),ie.uploadEvent({log:`stat-${rt.GET_USER_MEDIA_RETRY}-success-${s}`})}});function mh(s,i){return p(this,null,function*(){let t=(i?yield _t():yield ot()).find(r=>r.deviceId===s);t&&ne(t.getCapabilities)&&C.warn(gt(t.getCapabilities(),{keysToInclude:vn}))})}function J_(s){return{audio:j_(s),video:q_(s)}}function j_(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!oi(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(J(s.channelCount)&&(i.channelCount=s.channelCount),he(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),he(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),he(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),oi(i)?!0:i)}function q_(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!oi(e)?e:(s.width&&(e.width={ideal:s.width},i&&!ae&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!ae&&(e.height.max=s.height)),ae&&Mt&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),oi(e)?!0:e)}var hh=W_;function ya(s){return z((i,e)=>function(...t){return p(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Ke(s){return z((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function ba(s){return z((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function z(s){return function(i,e,t){return t.value=s(t.value,e),t}}var ph=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&C.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{C.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var X_=0,va=class{constructor(){d(this,"log",C.createLogger({id:`fq${++X_}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=v({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},$o=new WeakMap,Na=new WeakMap;function ni(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=$o.get(this)||new va;return $o.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function fh(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=$o.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let u=!0;return c.args.forEach(m=>{o.find(f=>f===m)||(u=!1)}),u?(c.reject(new y({code:S.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function Da(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,l;let n=[];return(c=(a=$o.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Na.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new y({code:S.API_CALL_ABORTED,message:s}))}),$o.delete(this),Na.delete(this),r.apply(this,o)},t}}function Li(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Na.get(this)||new Map,c=a.get(o(n))||new va;return a.set(o(n),c),Na.set(this,a),c.push({fn:r,args:n,context:this})},t}}function nt(s,i){return z((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=x();return Qi(n)?n.then(c=>(i?b.addSuccessEvent({key:o,cost:x()-a}):b.addSuccessEvent({key:o}),c)).catch(c=>{throw b.addFailedEvent({key:o,error:c}),c}):(b.addSuccessEvent({key:o}),n)}catch(n){throw b.addFailedEvent({key:o,error:n}),n}})}var Mr=class Mr extends kr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Ge(e,e).add(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){ve(e)}setStateToReady(){}capture(e){return p(this,null,function*(){var t;try{let r=x();E.emit(I.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield hh(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(I.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-r}),o}catch(r){throw E.emit(I.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(I.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&ei){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield uh({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),Sa().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&&!lh(this.mediaTrack)||this.kind===h.VIDEO&&!dh(this.mediaTrack)||this._isRecapturing||e&&Mt&&Le)}onTrackMuted(){if(super.onTrackMuted(),ph(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Yr){setTimeout(()=>this.onTrackMuted(),Yr);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ie||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Fe(Mr.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Yr){setTimeout(()=>this.onTrackEnded(),Yr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield ot():yield _t()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),E.emit(I.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),E.emit(I.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof Je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Ho.get(t)||0)+1;if(Ho.set(t,r),r>=3){let o=e?(yield _t()).find(n=>!Ho.has(n.deviceId)):(yield ot()).find(n=>!Ho.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)}};N([_e($.INIT,"ready",{ignoreError:!0,sync:!0})],Mr.prototype,"setStateToReady",1),N([ni()],Mr.prototype,"capture",1),N([_e("ready","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),E.emit(I.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let c=this.kind===h.AUDIO,l=this.stat.bytesSent>0;b[l?"addSuccessEvent":"addFailedEvent"]({key:c?503700:513702}),l||(b.addEnum({key:c?503701:513703,value:So()}),ie.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ar()||bi()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===S.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),nt(521714,!1)],Mr.prototype,"publish",1),N([z(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),_e([],"ready",{sync:!0})],Mr.prototype,"unpublish",1);var Mi=Mr,Ho=new Map;E.on(I.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&Ho.delete(s.track.deviceId)});var Et=class s extends Mi{constructor(e){super(1,Ca);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new We);d(this,"_output",new We);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Rs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Or.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return p(this,null,function*(){let t=this.trackSettings||{};b.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),b.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),b.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield Fe(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===fr){if(yield sl(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),E.emit(I.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){Me&&!Me.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Me.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),Ee(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield ot();t[0]?this.recapture(t[0].deviceId):Me.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(ae||Le?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&b.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Ie&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Re().createGain()),this._output.setNode(Re().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}addDenoiser(e){var t;if(dt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}b.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Me.off("audioInputAdded",this.handleMicrophoneAdded,this),Me.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Fe(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield ot()).find(o=>o.deviceId!==e);if(r)yield Fe(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Pi=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var Oa=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Pi(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((f,g)=>f+g.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),m=0;for(let f=0;f<n.length;f++)for(let g=0;g<n[f].dataView.byteLength;g++)l.setInt8(m++,n[f].dataView.getInt8(g));for(let f=0;f<i.data.byteLength;f++)l.setInt8(m++,u.getInt8(f));return i.data=c,n.length}return 0}};var Lr=class Lr extends Mi{constructor(e,t=4){super(t,pt);d(this,"profile",v({},ji));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Oa);this.manager=e;let r=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(w(v({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!ei||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return p(this,null,function*(){var t,r,o;if(K(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Fe(Lr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),Fe(Lr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=v({},e),r=t.width>t.height;t.width*t.height<=160*120&&pe&&Ye&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&md&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(Ye||ae)&&!pd()&&t.width*t.height<=640*360&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(w(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,o=this.settings;if(!(!(o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate)||!this.deviceId)&&(lt===16?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return ei&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:rs(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),E.emit(I.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}updateSmallConfig(e){var r,o;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=e,(r=this.manager)==null||r.update(),t&&((o=this.room)==null||o.enableSmall(!0)),this.log.info("update small stream config success")}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){Me&&!Me.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Me.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),Ee(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield _t();t[0]?this.recapture(t[0].deviceId):Me.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){Me.off("videoInputAdded",this.handleCameraAdded,this),Me.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Fe(Lr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield _t()).find(o=>o.deviceId!==e);if(r)yield Fe(Lr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};N([Ke(function(e){this.setContentHint(e.contentHint||"motion")})],Lr.prototype,"capture",1);var Je=Lr;var gh=Io();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gh,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var Z_=function(s){return p(this,null,function*(){let i=null,e=tg(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(ps&&dt<74||Le||ae)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield K_(r,s.captureElement))}if(s.audio){let o=eg(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function K_(s,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===gh))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function eg(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return T(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function tg(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Le?{max:s.width}:{ideal:s.width,max:s.width},height:Le?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var Th=Z_;var at=class extends Je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):m=yield Th({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof y?m:new y({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};N([Ke(function(e){this.setContentHint(e.contentHint||"detail")})],at.prototype,"capture",1);var ci=class extends Et{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var ig='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',nl;function Go(s,i=48e3,e){return p(this,null,function*(){let t=Re("dump");nl||(nl=Dr(t,URL.createObjectURL(new Blob([ig],{type:"application/javascript"})))),yield nl;let r=t.sampleRate,o=new AudioWorkletNode(t,"dumper",{numberOfInputs:s.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:r,targetSampleRate:i}});return e&&o.port.postMessage({port:e},[e]),s.forEach((n,a)=>n.connect(o,0,a)),new ReadableStream({start(n){o.port.onmessage=a=>{n.enqueue(a.data)}},cancel(){s.forEach(n=>n.disconnect(o)),o.port.close()}})})}var ka=class extends ga{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",C.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let f=0;f<r.length;f++){let g=URL.createObjectURL(new Blob(n[f])),D=document.createElement("a");D.href=g,D.download=`${r[f]}.pcm`,D.style.display="none",document.body.appendChild(D),D.click(),URL.revokeObjectURL(g),D.remove()}clearTimeout(a),o.abort("download")},l=Go(t).then(f=>f.pipeTo(new WritableStream({write(g){g.forEach((D,_)=>n[_]=n[_]?n[_].concat(D[0]):[D[0]])}}),o).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var O,re,Z;if(T(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:o=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(o*.04),l=new Float32Array(c),u=new Float32Array(c),m,f,g=0,D=new AbortController,_=t===""?(O=this._localAudioTrack)==null?void 0:O.mediaTrack:(Z=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:Z.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let A=Re().createMediaStreamSource(new MediaStream([_]));return Go([A],o,a).then(Y=>Y.pipeTo(new WritableStream({write(U){U[0][0]&&(g+U[0][0].length>c?(l.set(U[0][0].subarray(0,c-g),g),m=U[0][0].subarray(c-g),u.set(U[0][1].subarray(0,c-g),g),f=U[0][1].subarray(c-g),g+=c-g):(m&&(l.set(m,g),g+=m.length,m=void 0),f&&(u.set(f,g),f=void 0),l.set(U[0][0],g),u.set(U[0][1],g),g+=U[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:o,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),D).catch(U=>this.log.warn(`stop getPCM reason:${U}`))),D}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){if(e instanceof ci)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof Et)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof wi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof ci?delete this._localScreenAudioTrack:e instanceof Et?delete this._localAudioTrack:e instanceof wi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var o;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((o=this._localAudioTrack)==null||o.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(o=>{var n;(n=this.room)==null||n.emit("audio-frame",o)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){E.on("113",this.handleLocalTrackStarted,this),E.on("114",this.handleLocalTrackStopped,this),E.on("115",this.handleRemoteTrackStarted,this),E.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){E.off("113",this.handleLocalTrackStarted),E.off("114",this.handleLocalTrackStopped),E.off("115",this.handleRemoteTrackStarted),E.off("116",this.handleRemoteTrackStopped)}};function Ma(s=30,i=2){return z((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new y({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var Jl={};fi(Jl,{Events:()=>Ae,Inspect:()=>St,LastSink:()=>Pr,Sink:()=>G,Subscribe:()=>wr,TimeoutError:()=>Wo,audit:()=>Ug,bindCallback:()=>Ag,bindNodeCallback:()=>Cg,buffer:()=>ug,bufferCount:()=>lg,bufferTime:()=>iT,call:()=>Eh,catchError:()=>$l,combineLatest:()=>Ih,concat:()=>og,concatMap:()=>Xg,concatMapTo:()=>zg,count:()=>bg,create:()=>te,debounce:()=>Vg,debounceTime:()=>Bg,defer:()=>Ah,delay:()=>rT,deliver:()=>j,dispose:()=>La,elementAt:()=>Fg,empty:()=>qo,every:()=>Jg,exhaustMap:()=>Zg,exhaustMapTo:()=>Kg,filter:()=>di,find:()=>$g,findIndex:()=>Hg,first:()=>Gg,fromAnimationFrame:()=>Sg,fromArray:()=>pg,fromEvent:()=>me,fromEventPattern:()=>fg,fromFetch:()=>_g,fromIterable:()=>gg,fromPromise:()=>yh,fromReadableStream:()=>Eg,fromReader:()=>Tg,groupBy:()=>eT,identity:()=>rg,ignoreElements:()=>Og,iif:()=>ag,inspect:()=>Sh,interval:()=>hl,last:()=>Wg,map:()=>Xo,mapTo:()=>qg,max:()=>vg,merge:()=>ul,mergeMap:()=>Qg,mergeMapTo:()=>Yg,min:()=>Ng,never:()=>Rg,nothing:()=>de,of:()=>hg,pairwise:()=>jg,pipe:()=>le,race:()=>ml,range:()=>Ig,reduce:()=>pl,retry:()=>aT,scan:()=>Fl,share:()=>xi,shareReplay:()=>ng,skip:()=>Mg,skipUntil:()=>Lg,skipWhile:()=>Va,startWith:()=>Jo,subject:()=>et,subscribe:()=>ye,sum:()=>Dg,switchMap:()=>Ns,switchMapTo:()=>Ur,take:()=>Ui,takeLast:()=>kg,takeUntil:()=>xe,takeWhile:()=>bh,tap:()=>Wl,throttle:()=>wg,throwError:()=>yg,timeInterval:()=>tT,timeout:()=>nT,timer:()=>jo,toPromise:()=>sT,toReadableStream:()=>oT,withLatestFrom:()=>dg,zip:()=>cg});function de(...s){}var Eh=s=>s(),rg=s=>s;function La(){this.dispose()}var Sh=()=>typeof __FASTRX_DEVTOOLS__!="undefined",sg=1,St=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new al(i,this,this.streamId++);return Ae.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Pr=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=de,this.error=de,this.next=de,this.dispose=de,this.subscribe=de,this.doDefer()}subscribe(i){return i instanceof St?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Eh),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 Pr{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)}},wr=class extends Pr{constructor(i,e=de,t=de,r=de){if(super(),this._next=e,this._error=t,this._complete=r,this.then=de,i instanceof St){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ae.defer(o,0)}),Ae.create(o),Ae.pipe(o),this.sourceId=o.id,this.subscribe(i),Ae.subscribe({id:o.id,end:!0}),e==de?this._next=n=>Ae.next(o,0,n):this.next=n=>{Ae.next(o,0,n),e(n)},r==de?this._complete=()=>Ae.complete(o,0):this.complete=()=>{this.dispose(),Ae.complete(o,0),r()},t==de?this._error=n=>Ae.complete(o,0,n):this.error=n=>{this.dispose(),Ae.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 le(s,...i){return i.reduce((e,t)=>t(e),s)}function te(s,i,e){if(Sh()){let t=Object.defineProperties(Object.setPrototypeOf(s,St.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}});Ae.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof St&&Ae.addSource(t,o)}return t}return s}function j(s,i){return function(...e){return t=>{if(t instanceof St){let r=te(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Ae.pipe(r),r}else return r=>t(new s(r,...e))}}}function sr(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var al=class extends G{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ae.defer(this.source,this.id)})}next(i){Ae.next(this.source,this.id,i),this.sink.next(i)}complete(){Ae.complete(this.source,this.id),this.sink.complete()}error(i){Ae.complete(this.source,this.id,i),this.sink.error(i)}},Ae={addSource(s,i){sr("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){sr("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){sr("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){sr("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){sr("defer",{id:s.id,streamId:i})},pipe(s){sr("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){sr("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=sg++),sr("create",{name:s.toString(),id:s.id})}},Wo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Pa=class extends Pr{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function xi(){return s=>{let i=new Pa(s);if(s instanceof St){let e=te(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Ae.pipe(e),e}return te(i.add.bind(i),"share",arguments)}}function ul(...s){return te(i=>{let e=new G(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function ml(...s){return te(i=>{let e=new Map;s.forEach(t=>{let r=new G(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function og(...s){return te(i=>{let e=0,t=s.length,r=new G(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function ng(s){return i=>{let e=new Pa(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},te(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function ag(s,i,e){return te(t=>s()?i(t):e(t),"iif",arguments)}function Ih(...s){return te(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new G(i);u.next=m=>{--t===0?(u.next=f=>{o[l]=f,i.next(o)},u.next(m)):o[l]=m},u.complete=n,u.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function cg(...s){return te(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new G(i),u=[];r[c]=u,l.next=m=>{u.push(m),r.every(f=>f.length)&&i.next(r.map(f=>f.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Jo(...s){return i=>te((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var cl=class extends G{constructor(i,...e){super(i);let t=new G(this.sink);t.next=r=>this.buffer=r,t.complete=de,t.subscribe(Ih(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},dg=j(cl,"withLatestFrom"),dl=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()}},lg=j(dl,"bufferCount"),ll=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=de,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},ug=j(ll,"buffer");var mg=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?o(u.value):r(u.value).then(a,c)}l((t=t.apply(s,i||[])).next())})};function et(s){let i=arguments,e=xi()(te(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=de,e.complete=de,e.error=de,e}function Ah(s){return te(i=>i.subscribe(s()),"defer",arguments)}var Ch=s=>i=>{setTimeout(()=>s(i))},Rh=s=>Ch(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function hg(...s){return te(Rh(s),"of",arguments)}function pg(s){return te(Rh(s),"fromArray",arguments)}function hl(s){return te(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function jo(s,i){return te(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function wa(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function fg(s,i){return te(wa(s,i),"fromEventPattern",arguments)}function me(s,i){if("on"in s&&"off"in s)return te(wa(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return te(wa(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return te(wa(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function yh(s){return te(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function _g(s,i){return te(Ah(()=>yh(fetch(s,i))),"fromFetch",arguments)}function gg(s){return te(Ch(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function Tg(s){let i=e=>mg(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return te(e=>{i(e)},"fromReader",arguments)}function Eg(s){return te(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function Sg(){return te(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function Ig(s,i){return te((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function Ag(s,i,...e){return te(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function Cg(s,i,...e){return te(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function Rg(){return te(()=>{},"never",arguments)}function yg(s){return te(i=>i.error(s),"throwError",arguments)}function qo(){return te(s=>s.complete(),"empty",arguments)}var xr=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)}},pl=j(xr,"reduce"),bg=s=>j(xr,"count")((i,e)=>s(e)?i+1:i,0),vg=()=>j(xr,"max")(Math.max),Ng=()=>j(xr,"min")(Math.min),Dg=()=>j(xr,"sum")((s,i)=>s+i,0);var fl=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)}},di=j(fl,"filter"),_l=class extends G{next(i){}},Og=j(_l,"ignoreElements"),gl=class extends G{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Ui=j(gl,"take"),Tl=class extends G{constructor(i,e){super(i);let t=new G(i);t.next=()=>i.complete(),t.complete=La,t.subscribe(e)}},xe=j(Tl,"takeUntil"),El=class extends G{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},bh=j(El,"takeWhile"),kg=s=>pl((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),Sl=class extends G{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},Mg=j(Sl,"skip"),Il=class extends G{constructor(i,e){super(i),i.next=de;let t=new G(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=La,t.subscribe(e)}},Lg=j(Il,"skipUntil"),Al=class extends G{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Va=j(Al,"skipWhile"),Pg={leading:!0,trailing:!1},Cl=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)}},xa=class extends G{constructor(i,e,t=Pg){super(i),this.durationSelector=e,this.config=t,this._throttle=new Cl(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=de,this._throttle.complete(),super.complete()}},wg=j(xa,"throttle"),xg={leading:!1,trailing:!0},Ug=s=>j(xa,"audit")(s,xg),Rl=class extends G{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ua=class extends G{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Rl(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()}},Vg=j(Ua,"debounce"),Bg=s=>j(Ua,"debounceTime")(i=>jo(s)),yl=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()}},Fg=j(yl,"elementAt"),$g=s=>i=>Ui(1)(Va(e=>!s(e))(i)),bl=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}},Hg=j(bl,"findIndex"),vl=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()}},Gg=j(vl,"first"),Nl=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()}},Wg=j(Nl,"last"),Dl=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()}},Jg=j(Dl,"every");var Ol=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))}},Fl=j(Ol,"scan"),kl=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}},jg=j(kl,"pairwise"),Ba=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))}},Xo=j(Ba,"map"),qg=s=>j(Ba,"mapTo")(i=>s),bs=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()}},vs=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()}},Fa=class extends bs{},$a=class extends vs{next(i){this.subInner(i,Fa),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Fa)}}},Ns=j($a,"switchMap");function Ja(s){return(i,e)=>s(()=>i,e)}var Ur=Ja(j($a,"switchMapTo")),Ml=class extends bs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Ha=class extends vs{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(),Ml),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},Xg=j(Ha,"concatMap"),zg=Ja(j(Ha,"concatMapTo")),Ll=class extends bs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Ga=class extends vs{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Ll),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},Qg=j(Ga,"mergeMap"),Yg=Ja(j(Ga,"mergeMapTo")),Pl=class extends bs{dispose(){this.context.resetNext(),super.dispose()}},Wa=class extends vs{next(i){this.next=de,this.subInner(i,Pl)}},Zg=j(Wa,"exhaustMap"),Kg=Ja(j(Wa,"exhaustMapTo")),wl=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=et(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},eT=j(wl,"groupBy"),xl=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}},tT=j(xl,"timeInterval"),Ul=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()}},iT=j(Ul,"bufferTime"),Vl=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)}},rT=j(Vl,"delay"),Bl=class extends G{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},$l=j(Bl,"catchError");var sT=()=>s=>new Promise((i,e)=>{let t;new wr(s,r=>t=r,e,()=>i(t))}),oT=()=>s=>{let i;return new ReadableStream({start(e){i=new wr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},ye=(s=de,i=de,e=de)=>t=>new wr(t,s,i,e),Hl=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)}))}},Wl=j(Hl,"tap"),Gl=class extends G{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Wo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},nT=j(Gl,"timeout"),aT=(s=1/0)=>i=>{if(i instanceof St){let e=te(t=>{let r=s,o=new G(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,Ae.pipe(e),e}else return e=>{let t=s,r=new G(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var li=class li extends kr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",et(me(this,li.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new $(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new $(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),le(ul(me(this,$.STATECHANGED),me(this.remotePublishState,$.STATECHANGED)),Xo(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),ye(c=>{this.availableState.state!==(c?$.ON:$.OFF)&&(this.availableState.state=c?$.ON:$.OFF),this.updatePlayingState(c)}));let o=le(me(this.player,ue.ERROR),di(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=le(jo(5e3),di(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===h.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=le(ml(o,n),xe(me(this,$.INIT)));le(this._triggerCheckDecodeSubject,di(()=>!this.ignoreDecodeError),Ur(a),ye(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===li.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===$.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===h.AUDIO;b[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(b.addEnum({key:r?504701:514703,value:So()}),ie.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ar()||bi()}`,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}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?$.ON:$.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(li,"STATE_SUBSCRIBE","subscribe"),N([Ma(5,1)],li.prototype,"waitHasMediaTrack",1),N([_e($.INIT,li.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),E.emit(I.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),nt(521716,!1)],li.prototype,"subscribe",1),N([_e(li.STATE_SUBSCRIBE,$.INIT,{sync:!0,success(){this.log.info("unsubscribed"),E.emit(I.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],li.prototype,"unsubscribe",1);var Ds=li;var wi=class extends Ds{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Or.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var dT=[-1,-1,1,-1,-1,1,1,1],lT=[0,0,1,0,0,1,1,1];var tt=class extends ${constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof je){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&lt!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(lT),this.positionBuffer=this.createBuffer(dT),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Oe&&this.render(e)||this.context instanceof je&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Oe){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:u,name:a,cost:c},v({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([_e($.INIT,"connected",{sync:!0})],tt.prototype,"connect",1),N([_e("connected",$.INIT,{ignoreError:!0,sync:!0})],tt.prototype,"disconnect",1),N([_e([],"closed",{sync:!0})],tt.prototype,"close",1);var uT=le(hl(250),Xo(()=>performance.now()),xi());var Nh=s=>i=>{let e=performance.now();le(uT,Va(t=>t-e<s),Ui(1))(i)};var hT=[0,1,1,1,0,0,1,0],Vr=class extends tt{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof je?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(hT)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Oe){let r=this.context.ctx.getError();r&&this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(oe.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),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Os=class extends Vr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",me(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Ri)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=me(this._videoTrack,"mute"),le(me(this._videoTrack,"ended"),xe(this._closedOb),ye(()=>{this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=le(this._muteOb,xe(this._closedOb),Ur(Nh(5e3)),di(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),ye(()=>{this.context.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},ja=class extends Os{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var qa=class extends Os{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 zo=class extends tt{constructor(e,t){super(e,v({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);d(this,"waitingFirstFrame",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,lt===16&&(this._canvasRendered=et(),le(this._canvasRendered,Jo(this._image),Ns(r=>r instanceof HTMLCanvasElement?me(r,"rendered"):qo()),xe(me(this,"closed")),ye(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Nr()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Qo=class extends zo{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",le(me(this._player,ue.PLAYER_STATE_CHANGED),xe(me(this,"closed")),di(({state:o})=>o==="PLAYING"),ye(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Vi=class extends Qo{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new pt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var fT=`
34
+ `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=mu,r.innerText=`${mi()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${Cd}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){_u()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Eo}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",z.info("show autoplay dialog"),Me.uploadEvent({log:gE}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){z.warn("confirm clicked, try resume stream"),x.emit(B.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Ap}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Me.uploadEvent({log:EE}),this._isCollapseClicked=!0}onQuestionClick(){window.open(bp,"_blank"),this._isQuestionClicked||Me.uploadEvent({log:TE}),this._isQuestionClicked=!0}},vp=pu;var Zt=class extends Ji{constructor(e){super(e,S.VIDEO);c(this,"stat",{});c(this,"_calculateTimeout",-1);c(this,"viewMirror",!1);c(this,"objectFit");c(this,"container");c(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,M(e.viewMirror)||(this.viewMirror=e.viewMirror),M(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(S.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(S.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(S.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===S.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,o;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===S.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=ls,this._log.info(`view container ${(o=this.container)==null?void 0:o.id} is recreated`)),this._pausedRetryCount>0&&!_u()&&(this._log.info(`[${ls-this._pausedRetryCount+1}/${ls}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===S.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===S.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((o=this.element)==null||o.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Ge.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(ys()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function Rr(s,i){return A(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),z.info("worklet addModule success")}catch(e){throw z.info(`worklet addModule catch error. ${e.message}`),e}})}var Fn;typeof AudioContext!="undefined"?Fn=AudioContext:typeof webkitAudioContext!="undefined"?Fn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Fn=mozAudioContext);var Ai,Np=-1;Dp();function Dp(){try{if(Ai)return;Ai=new Fn({sampleRate:48e3}),Ai.onstatechange=()=>{z.info(`context state: ${Ai.state}${Ai.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),To()},clearTimeout(Np)}catch(s){z.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof Fn}`),Np=setTimeout(Dp,1e3)}}var To=()=>{Ai.state==="suspended"?(So(),document.addEventListener("click",To)):Ai.state==="interrupted"?So():(document.removeEventListener("visibilitychange",To),document.removeEventListener("click",To))},gu=0,Eu=-1;function So(){return new Promise((s,i)=>{if(Ai.state==="running")return s();Date.now()-gu<1e3?(clearTimeout(Eu),Eu=setTimeout(()=>{gu=Date.now(),Ai.resume().then(s,i)},1e3)):(clearTimeout(Eu),gu=Date.now(),Ai.resume().then(s,i))}).catch(s=>{z.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",To)})}document.addEventListener("click",To);var dt=s=>Ai;var ct=class{constructor(i){c(this,"name");c(this,"node");c(this,"node2");c(this,"pre",new Set);c(this,"next",new Set);c(this,"context");c(this,"connectedNodes",new Set);c(this,"nextInputChannelMap",new Map);c(this,"_channelCount",1);this.name=i}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){z.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),Q.addSuccessEvent({key:502701})}catch(r){z.error(r),Q.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),Q.addSuccessEvent({key:502702})}catch(e){z.error(e),Q.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yd=class extends ct{constructor(e=256){super();this.fftSize=e;c(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Hn=class{constructor(){c(this,"source",new ct);c(this,"gain",new ct);c(this,"destination",new ct)}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(dt().createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.replaceNode(Gn(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}},Io=class extends Hn{constructor(e){super();this.context=e;c(this,"audioProcessor",new ct("aec"));c(this,"mixNode",new ct("mixNode"));c(this,"muteNode",new ct("muteNode"));c(this,"denoiser",new ct);c(this,"voiceChanger",new ct);this.source.pipeTo(this.audioProcessor).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.muteNode.pipeTo(this.mixNode).pipeTo(this.audioProcessor,1)}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.audioProcessor.setContext(this.context),this.muteNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.audioProcessor.removeContext(),this.muteNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.audioProcessor.deleteNode(),this.muteNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bd=class{constructor(){c(this,"audioContext",dt("audio-mixer"));c(this,"destination",this.audioContext.createMediaStreamDestination());c(this,"inputs",new Set);c(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},kp=new WeakMap;function Gn(s){let i=kp.get(s);if(i)return i;let e=dt();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return kp.set(s,i),i}var Kt=class Kt{constructor(i){c(this,"_volume",0);c(this,"_volumeDb",0);c(this,"_log");c(this,"_scriptProcessorNode",null);c(this,"_audioWorkletNode",null);c(this,"_interval",200);c(this,"ready",this.preload());let{log:e}=i;this._log=e,x.on(B.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Kt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Kt.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Kt.workletReady=Rr(Kt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Kt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Kt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Kt.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}`),Me.logFailedEvent({userId:this._log.userId,eventType:Ft.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=dt("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Kt.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,x.off(B.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};c(Kt,"lastMessageTime",0),c(Kt,"audioContext",dt("volume-meter")),c(Kt,"workletReady");var vd=Kt,Nd=class extends ct{constructor(e){super();c(this,"_volumeMeter");this._volumeMeter=new vd(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return A(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()}}},bs=vd;var xp=gt(Mt(),1);var wp=s=>i=>i.deviceId===s;var Wn=class{constructor(i,e="Input"){c(this,"kind");c(this,"type");c(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Ao(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(wp(r.deviceId))){let o=`${this.kind}${this.type}Added`;z.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(wp(r.deviceId))){let o=`${this.kind}${this.type}Removed`;z.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Tu=class extends xp.EventEmitter{constructor(){super();c(this,"audioInputs",new Wn(S.AUDIO));c(this,"videoInputs",new Wn(S.VIDEO));c(this,"audioOutputs",new Wn(S.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Le.run("interval",()=>{this.update()},{delay:1e4}))}init(){Dd().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return A(this,arguments,function*(e=0){let t=yield Dd(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ft=en||js?null:new Tu;function Ao(s){return s.deviceId===s.groupId&&s.groupId===""}function Dd(){return A(this,arguments,function*(s=0){if(Ir()||!gd())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Ao(t)&&(t.kind===S.AUDIO_INPUT?e.audio=!0:t.kind===S.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&So()}catch(r){z.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&&Su.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function Wt(s=!1){return ft.update(s?1:0).then(i=>i.audioInputs.devices)}function ei(s=!1){return ft.update(s?2:0).then(i=>i.videoInputs.devices)}var Mp=!1;function Lp(){return A(this,null,function*(){try{Mp||(Mp=!0,z.info(`speakers:${(yield Yr()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function Yr(s=!1){return A(this,null,function*(){return(Ye||pt)&&(s=!1),ft.update(s?1:0).then(i=>i.audioOutputs.devices)})}var Su=new Set;function Pp(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}_${S.VIDEO_INPUT}`;return!!Su.has(t)}function Up(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}_${S.AUDIO_INPUT}`;return!!Su.has(t)}function Iu(s,i){return A(this,null,function*(){let t=(yield Wt()).find(r=>r.deviceId===us);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function Vp(o){return A(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===S.AUDIO&&s===us?yield Iu(e,t):!0})}var kd,Au=class extends Hn{constructor(e){super();this.log=e;c(this,"volumeMeter");c(this,"volumeDestination");c(this,"analyser",new yd);this.volumeMeter=new Nd({log:this.log}),this.volumeDestination=new ct,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Od=class s extends Ji{constructor(e){super(e,S.AUDIO);c(this,"_outputDeviceId");c(this,"_volume",1);c(this,"_destination",dt("player").createMediaStreamDestination());c(this,"pipeline");c(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Au(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Bi==="15.2"||Bi==="15.3"||Bi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=kd||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,De(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===kd&&(kd=void 0),this.bindElementEvents()}play(e){return A(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(dt("player").createAnalyser()),Lp(),Ct(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return A(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()}},wd=class extends Od{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Ge.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Md=class extends Od{constructor(e){super(e);c(this,"_sourceElement");c(this,"_output",new ct);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(dt("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(Ge.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):Ye||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),at(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&jr&&(kd=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var vs=class extends ge{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?Md:Zt}){var a;super();c(this,"id",yn());c(this,"userId","");c(this,"isRemote");c(this,"mediaType");c(this,"room");c(this,"user");c(this,"_log");c(this,"_inputTrack");c(this,"_outputTrack");c(this,"isPlayCalled");c(this,"container",null);c(this,"player");c(this,"subVideoPlayerMap");c(this,"muted",!1);c(this,"abortCtrl");c(this,"objectFit","cover");c(this,"mirror");c(this,"isScreen",!1);c(this,"manager");c(this,"trackSettings");c(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=z.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof yr?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof yr}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Ge.PLAYER_STATE_CHANGED,d=>{x.emit(B.PLAYER_STATE_CHANGED,Z({track:this},d)),this.emit("player-state-changed",d)}),this.kind===S.VIDEO&&(this.player.on(Ge.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Ge.LOADED_DATA),x.emit(B.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Ge.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Ge.LOADED_META_DATA)}),this.player.on(Ge.MEDIA_TRACK_CHANGED,d=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(h=>h.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(Ge.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||z}get kind(){return this.mediaType===1?S.AUDIO:S.VIDEO}get strMediaType(){return this.mediaType===4?S.VIDEO:this.mediaType===2?S.SCREEN:S.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 A(this,null,function*(){let r=tt(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!M(t.muted)&&this.setPlayerMute(t.muted),t&&!M(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),tt(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!M(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===S.VIDEO)&&this.setPlayerMute(!0),t&&!M(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),t&&!M(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof Zt&&this.player.setContainer(r)),x.emit(B.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),tt(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==S.VIDEO||M(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(Qe(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 A(this,null,function*(){if(!this._outputTrack||this.kind===S.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&&(M(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new Zt({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(_l(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return A(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),x.emit(e?B.TRACK_MUTED:B.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){vt(e,e).add(S.MUTE,this.onTrackMuted).add(S.UNMUTE,this.onTrackUnmuted).add(S.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===S.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){at(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(_l(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new vp;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof Zt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,d;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((d=this.player.element)==null?void 0:d.videoHeight)||0;e===Ge.LOADED_META_DATA&&!r&&!o||(e===Ge.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:r,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};J([qe([],ge.INIT,{sync:!0})],vs.prototype,"close",1);var IE=Object.prototype.hasOwnProperty,{toString:ty}=Object.prototype;function AE(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(Ht(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(IE.call(s,i))return!1;return!0}}return!1}var qi=AE;var CE=function(s){return A(this,null,function*(){let i=yE(s);z.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield Wt(),z.info(`microphones: ${oi(e.map(o=>de(Z({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield ei(),z.info(`cameras: ${oi(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return su&&o.getTracks().forEach(n=>{z.info(`${n.kind} capabilities: ${oi(n.getCapabilities(),{keysToInclude:La})}`)}),i.audio&&So(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=pe({key:me.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=pe({key:me.MICROPHONE_NOT_FOUND}))),new X({code:H.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},RE=Ui({retryFunction:CE,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,(!pt||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&&Bp(t[0].microphoneId,!1),t[0].cameraId&&Bp(t[0].cameraId,!0)},onRetrying:s=>{z.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{Me.logFailedEvent({eventType:Ft.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{Me.logSuccessEvent({eventType:Ft.GET_USER_MEDIA_RETRY}),Me.uploadEvent({log:`stat-${Ft.GET_USER_MEDIA_RETRY}-success-${s}`})}});function Bp(s,i){return A(this,null,function*(){let t=(i?yield ei():yield Wt()).find(r=>r.deviceId===s);t&&Fe(t.getCapabilities)&&z.warn(oi(t.getCapabilities(),{keysToInclude:La}))})}function yE(s){return{audio:bE(s),video:vE(s)}}function bE(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!qi(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(De(s.channelCount)&&(i.channelCount=s.channelCount),Qe(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),Qe(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),Qe(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),qi(i)?!0:i)}function vE(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&&!qi(e)?e:(s.width&&(e.width={ideal:s.width},i&&!Ue&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!Ue&&(e.height.max=s.height)),Ue&&Ei&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),qi(e)?!0:e)}var $p=RE;function xd(s){return be((i,e)=>function(...t){return A(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Ut(s){return be((i,e)=>function(...t){return A(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function Ld(s){return be((i,e)=>function(...t){return A(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function be(s){return function(i,e,t){return t.value=s(t.value,e),t}}var Fp=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&z.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{z.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var NE=0,Pd=class{constructor(){c(this,"log",z.createLogger({id:`fq${++NE}`}));c(this,"isRunning",!1);c(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=Z({},i),r=new Promise((a,d)=>{t.resolve=a,t.reject=d});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},zn=new WeakMap,Ud=new WeakMap;function Xi(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=zn.get(this)||new Pd;return zn.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function Hp(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=zn.get(this);if(n){let a=n.queue.filter((d,l)=>{if(l===0)return!0;let h=!0;return d.args.forEach(u=>{o.find(m=>m===u)||(h=!1)}),h?(d.reject(new X({code:H.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function Vd(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,d,l;let n=[];return(d=(a=zn.get(this))==null?void 0:a.queue)==null||d.forEach(h=>n.push(h)),(l=Ud.get(this))==null||l.forEach(h=>h==null?void 0:h.queue.forEach(u=>n.push(u))),n.forEach(h=>{h.reject(new X({code:H.API_CALL_ABORTED,message:s}))}),zn.delete(this),Ud.delete(this),r.apply(this,o)},t}}function br(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Ud.get(this)||new Map,d=a.get(o(n))||new Pd;return a.set(o(n),d),Ud.set(this,a),d.push({fn:r,args:n,context:this})},t}}function zt(s,i){return be((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=le();return Wr(n)?n.then(d=>(i?Q.addSuccessEvent({key:o,cost:le()-a}):Q.addSuccessEvent({key:o}),d)).catch(d=>{throw Q.addFailedEvent({key:o,error:d}),d}):(Q.addSuccessEvent({key:o}),n)}catch(n){throw Q.addFailedEvent({key:o,error:n}),n}})}var Ns=class Ns extends vs{constructor(e,t){super({mediaType:e,PlayerClass:t});c(this,"isRemote",!1);c(this,"deviceId");c(this,"groupId","");c(this,"label","");c(this,"sourceTrack");c(this,"_isRecapturing",!1);c(this,"_lastRecaptureTime",0);c(this,"_onMuteTimeoutId",-1);c(this,"_encodeCheckTimeoutId",-1);c(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){vt(e,e).add(S.MUTE,this.onTrackMuted).add(S.UNMUTE,this.onTrackUnmuted).add(S.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===S.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){at(e)}setStateToCapture(){}capture(e){return A(this,null,function*(){var t;try{let r=le();x.emit(B.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 $p(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),x.emit(B.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:le()-r}),o}catch(r){throw x.emit(B.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===ge.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),x.emit(B.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return A(this,null,function*(){if(this.mediaTrack&&Gi){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield Vp({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),Dd().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===S.AUDIO&&!Up(this.mediaTrack)||this.kind===S.VIDEO&&!Pp(this.mediaTrack)||this._isRecapturing||e&&Ei&&pt)}onTrackMuted(){if(super.onTrackMuted(),Fp(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Xs){setTimeout(()=>this.onTrackMuted(),Xs);return}this._onMuteTimeoutId=setTimeout(()=>A(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ye||ze)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return A(this,null,function*(){if(Ct(Ns.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Xs){setTimeout(()=>this.onTrackEnded(),Xs);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return A(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 Wt():yield ei()).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}),x.emit(B.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),x.emit(B.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return A(this,null,function*(){let e=this instanceof Nt;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(jn.get(t)||0)+1;if(jn.set(t,r),r>=3){let o=e?(yield ei()).find(n=>!jn.has(n.deviceId)):(yield Wt()).find(n=>!jn.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)}};J([qe(ge.INIT,"capture",{ignoreError:!0,sync:!0})],Ns.prototype,"setStateToCapture",1),J([Xi()],Ns.prototype,"capture",1),J([qe("capture","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),x.emit(B.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let d=this.kind===S.AUDIO,l=this.stat.bytesSent>0;Q[l?"addSuccessEvent":"addFailedEvent"]({key:d?503700:513702}),l||(Q.addEnum({key:d?503701:513703,value:Rn()}),Me.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ts()||gr()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===H.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),zt(521714,!1)],Ns.prototype,"publish",1),J([be(e=>function(){return A(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),qe([],"capture",{sync:!0})],Ns.prototype,"unpublish",1);var yr=Ns,jn=new Map;x.on(B.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&jn.delete(s.track.deviceId)});var ti=class s extends yr{constructor(e){super(1,wd);c(this,"mediaType",1);c(this,"volume",0);c(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});c(this,"playerMuted",!0);c(this,"pipeline");c(this,"earMonitorGainNode",new ct);c(this,"_output",new ct);c(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});c(this,"mixedAudioReferenceMap",new Map);this.manager=e,this.pipeline=new Io(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return bs.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return A(this,null,function*(){let t=this.trackSettings||{};Q.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),Q.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),Q.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 Ct(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return A(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===us){if(yield Iu(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}),x.emit(B.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(){ft&&!ft.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ft.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return A(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),Ze(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Wt();t[0]?this.recapture(t[0].deviceId):ft.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return A(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),d=!1;!M(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,d=!0),!M(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,d=!0),!M(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,d=!0),d&&(Ue||pt?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&Q.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Ye&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(dt().createGain()),this._output.setNode(dt().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this._inputTrack&&!(pt||Ye))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(qt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Q.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=Gn(e),o=new ct,n=dt().createGain();n.gain.value=1;let a=new ct;o.pipeTo(a).pipeTo(this.pipeline.mixNode),o.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[o,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,o]=this.mixedAudioReferenceMap.get(e)||[];o!=null&&o.node&&(o.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${o.node.gain.value}`))}addAudioProcessor(e,t,r,o){this.pipeline.muteNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.audioProcessor.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}removeAudioProcessor(e,t,r,o){this.pipeline.audioProcessor.node===e&&(this.pipeline.audioProcessor.deleteNode(),this.pipeline.muteNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),ft.off("audioInputAdded",this.handleMicrophoneAdded,this),ft.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return A(this,null,function*(){try{yield Ct(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield Wt()).find(o=>o.deviceId!==e);if(r)yield Ct(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var vr=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 Bd=class{constructor(){c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new vr(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,p)=>m+p.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),l=new DataView(d),h=new DataView(i.data),u=0;for(let m=0;m<n.length;m++)for(let p=0;p<n[m].dataView.byteLength;p++)l.setInt8(u++,n[m].dataView.getInt8(p));for(let m=0;m<i.data.byteLength;m++)l.setInt8(u++,h.getInt8(m));return i.data=d,n.length}return 0}};var Ds=class Ds extends yr{constructor(e,t=4){super(t,Zt);c(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});c(this,"avoidCropping",!1);c(this,"_scaleResolutionDownBy");c(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});c(this,"small");c(this,"isNeedToSetBandwidth");c(this,"muteImage");c(this,"manager");c(this,"_seiCodec",new Bd);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(de(Z({},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(!(!Gi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return A(this,null,function*(){var t,r,o;if(Oe(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,Ct(Ds.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ct(Ds.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=Z({},e),r=t.width>t.height;t.width*t.height<=160*120&&ze&&xt&&(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&&Dl&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(xt||Ue)&&!Ol()&&t.width*t.height<=640*360&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(de(Z({},this.profile),{width:1920,height:1080})))}applyProfile(){return A(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,o=this.settings;if(!(!(o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate)||!this.deviceId)&&(Xt===16?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){this.isNeedToSetBandwidth=!1;let{width:d=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),h=d*l;if(h&&r&&h===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:S.VIDEO,videoType:S.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return Gi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Va()&&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 A(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),x.emit(B.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(){ft&&!ft.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ft.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return A(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),Ze(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield ei();t[0]?this.recapture(t[0].deviceId):ft.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return A(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return M(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){ft.off("videoInputAdded",this.handleCameraAdded,this),ft.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return A(this,null,function*(){try{yield Ct(Ds.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield ei()).find(o=>o.deviceId!==e);if(r)yield Ct(Ds.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};J([Ut(function(e){this.setContentHint(e.contentHint||"motion")})],Ds.prototype,"capture",1);var Nt=Ds;var Wp=yn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Wp,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var wE=function(s){return A(this,null,function*(){let i=null,e=LE(s);z.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(ho&&qt<74||pt||Ue)&&z.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){z.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield ME(r,s.captureElement))}if(s.audio){let o=xE(s);z.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function ME(s,i){return A(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Fe(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===Wp))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){z.warn(`cropTo target failed ${t}`)}})}function xE(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return M(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function LE(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:pt?{max:s.width}:{ideal:s.width,max:s.width},height:pt?{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 zp=wE;var jt=class extends Nt{constructor(e){super(e,2);c(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});c(this,"objectFit","contain");c(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(h){return A(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:l}){try{let u;return a||n?(u=new MediaStream,a&&u.addTrack(a),n&&u.addTrack(n)):u=yield zp({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:d,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(u.getVideoTracks()[0]),u}catch(u){throw this.log.error(`getDisplayMedia error observed ${u}`),u instanceof X?u:new X({code:H.INITIALIZE_FAILED,name:u.name,message:u.message})}})}switchDevice(e){return A(this,null,function*(){throw new Error("Method not implemented.")})}};J([Ut(function(e){this.setContentHint(e.contentHint||"detail")})],jt.prototype,"capture",1);var Yi=class extends ti{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t,r){this.pipeline.muteNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.audioProcessor.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(i,e,t,r){this.pipeline.audioProcessor.node===r&&(this.pipeline.audioProcessor.deleteNode(),this.pipeline.muteNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var PE="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Cu;function Jn(s){return A(this,null,function*(){let i=dt("dump");Cu||(Cu=Rr(i,URL.createObjectURL(new Blob([PE],{type:"application/javascript"})))),yield Cu;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 $d=class extends bd{constructor(e){super();this.room=e;c(this,"_localAudioTrack");c(this,"_localScreenAudioTrack");c(this,"log",z.createLogger({id:"am"}));c(this,"denoiser");c(this,"voiceChanger");c(this,"mixChangedDebounce");c(this,"audioProcessor");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);c(this,"audioReferenceMap",new Map);c(this,"isLocalAudioNeedAudioProcess",!1);c(this,"isScreenAudioNeedAudioProcess",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.handleAudioReferenceChanged=this.handleAudioReferenceChanged.bind(this),x.on(B.AUDIO_PROCESSOR_REFERENCE_CHANGED,this.handleAudioReferenceChanged)}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var h,u;if(!this._localAudioTrack)return;let t=[],r=[];(h=this._localAudioPipline)!=null&&h.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(u=this._localAudioPipline)!=null&&u.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),d=()=>{for(let m=0;m<r.length;m++){let p=URL.createObjectURL(new Blob(n[m])),g=document.createElement("a");g.href=p,g.download=`${r[m]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(p),g.remove()}clearTimeout(a),o.abort("download")},l=Jn(t).then(m=>m.pipeTo(new WritableStream({write(p){p.forEach((g,f)=>n[f]=n[f]?n[f].concat(g[0]):[g[0]])}}),o).catch(p=>d));return{then:l.then.bind(l),download:d}}getPCM(e){var n;if(M(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 Jn([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(d){d[0][0]&&(t.set(d[0][0],r),r+=d[0][0].length,r>=1920&&(r=0,e(t),t=new Float32Array(1920)))}}),o).catch(d=>this.log.warn(`stop getPCM reason:${d}`))),o}get hasScreenAudioTrack(){return!M(this._localScreenAudioTrack)}get hasAudioTrack(){return!M(this._localAudioTrack)}changeInput(e){if(e instanceof Yi)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof ti)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ci)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Yi?delete this._localScreenAudioTrack:e instanceof ti?delete this._localAudioTrack:e instanceof Ci}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,o){var n;this.audioProcessor=[e,t,r,o],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,d)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,d)}))}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t,r,o){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,t,r,o)}destroy(){x.off(B.AUDIO_PROCESSOR_REFERENCE_CHANGED,this.handleAudioReferenceChanged),this.close()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleAudioReferenceChanged({room:e,type:t,audioReference:r,refId:o,volume:n}){if(e===this.room){if(t==="add"){if(this.audioReferenceMap.get(o)||!r||(this.audioReferenceMap.set(o,r),!this.audioProcessor))return;this.mixAudioReference(r,o)}else if(t==="remove")this.audioReferenceMap.get(o)&&(this.audioReferenceMap.delete(o),this.unMixAudioReference(o));else if(t==="update_volume"){if(!this.audioProcessor||M(n))return;this.setAudioReferenceVolume(o,n)}}}checkScreenAudioEchoCancellation(){}};function Fd(s=30,i=2){return be((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let d=new X({code:H.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});z.warn(d),i===2?n(d):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var dh={};nr(dh,{Events:()=>Ke,Inspect:()=>di,LastSink:()=>ks,Sink:()=>Te,Subscribe:()=>Os,TimeoutError:()=>qn,audit:()=>gT,bindCallback:()=>iT,bindNodeCallback:()=>rT,buffer:()=>zE,bufferCount:()=>WE,bufferTime:()=>PT,call:()=>jp,catchError:()=>sh,combineLatest:()=>qp,concat:()=>BE,concatMap:()=>NT,concatMapTo:()=>DT,count:()=>nT,create:()=>we,debounce:()=>ET,debounceTime:()=>TT,defer:()=>Xp,delay:()=>UT,deliver:()=>Ae,dispose:()=>Hd,elementAt:()=>ST,empty:()=>Yn,every:()=>yT,exhaustMap:()=>wT,exhaustMapTo:()=>MT,filter:()=>Zi,find:()=>IT,findIndex:()=>AT,first:()=>CT,fromAnimationFrame:()=>eT,fromArray:()=>qE,fromEvent:()=>We,fromEventPattern:()=>XE,fromFetch:()=>QE,fromIterable:()=>YE,fromPromise:()=>Zp,fromReadableStream:()=>KE,fromReader:()=>ZE,groupBy:()=>xT,identity:()=>UE,ignoreElements:()=>lT,iif:()=>FE,inspect:()=>Jp,interval:()=>ku,last:()=>RT,map:()=>Zn,mapTo:()=>vT,max:()=>aT,merge:()=>Nu,mergeMap:()=>kT,mergeMapTo:()=>OT,min:()=>dT,never:()=>sT,nothing:()=>$e,of:()=>JE,pairwise:()=>bT,pipe:()=>He,race:()=>Du,range:()=>tT,reduce:()=>Ou,retry:()=>FT,scan:()=>rh,share:()=>Nr,shareReplay:()=>$E,skip:()=>hT,skipUntil:()=>mT,skipWhile:()=>Jd,startWith:()=>Xn,subject:()=>Vt,subscribe:()=>it,sum:()=>cT,switchMap:()=>yo,switchMapTo:()=>Ms,take:()=>Dr,takeLast:()=>uT,takeUntil:()=>St,takeWhile:()=>Kp,tap:()=>ah,throttle:()=>fT,throwError:()=>oT,timeInterval:()=>LT,timeout:()=>$T,timer:()=>Qn,toPromise:()=>VT,toReadableStream:()=>BT,withLatestFrom:()=>GE,zip:()=>HE});function $e(...s){}var jp=s=>s(),UE=s=>s;function Hd(){this.dispose()}var Jp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",VE=1,di=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Ru(i,this,this.streamId++);return Ke.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ks=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=$e,this.error=$e,this.next=$e,this.dispose=$e,this.subscribe=$e,this.doDefer()}subscribe(i){return i instanceof di?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(jp),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}},Te=class extends ks{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)}},Os=class extends ks{constructor(i,e=$e,t=$e,r=$e){if(super(),this._next=e,this._error=t,this._complete=r,this.then=$e,i instanceof di){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ke.defer(o,0)}),Ke.create(o),Ke.pipe(o),this.sourceId=o.id,this.subscribe(i),Ke.subscribe({id:o.id,end:!0}),e==$e?this._next=n=>Ke.next(o,0,n):this.next=n=>{Ke.next(o,0,n),e(n)},r==$e?this._complete=()=>Ke.complete(o,0):this.complete=()=>{this.dispose(),Ke.complete(o,0),r()},t==$e?this._error=n=>Ke.complete(o,0,n):this.error=n=>{this.dispose(),Ke.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 He(s,...i){return i.reduce((e,t)=>t(e),s)}function we(s,i,e){if(Jp()){let t=Object.defineProperties(Object.setPrototypeOf(s,di.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}});Ke.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof di&&Ke.addSource(t,o)}return t}return s}function Ae(s,i){return function(...e){return t=>{if(t instanceof di){let r=we(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Ke.pipe(r),r}else return r=>t(new s(r,...e))}}}function Zr(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var Ru=class extends Te{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ke.defer(this.source,this.id)})}next(i){Ke.next(this.source,this.id,i),this.sink.next(i)}complete(){Ke.complete(this.source,this.id),this.sink.complete()}error(i){Ke.complete(this.source,this.id,i),this.sink.error(i)}},Ke={addSource(s,i){Zr("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){Zr("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){Zr("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){Zr("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){Zr("defer",{id:s.id,streamId:i})},pipe(s){Zr("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){Zr("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=VE++),Zr("create",{name:s.toString(),id:s.id})}},qn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Gd=class extends ks{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 Nr(){return s=>{let i=new Gd(s);if(s instanceof di){let e=we(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Ke.pipe(e),e}return we(i.add.bind(i),"share",arguments)}}function Nu(...s){return we(i=>{let e=new Te(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function Du(...s){return we(i=>{let e=new Map;s.forEach(t=>{let r=new Te(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function BE(...s){return we(i=>{let e=0,t=s.length,r=new Te(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function $E(s){return i=>{let e=new Gd(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},we(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function FE(s,i,e){return we(t=>s()?i(t):e(t),"iif",arguments)}function qp(...s){return we(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(d,l)=>{let h=new Te(i);h.next=u=>{--t===0?(h.next=m=>{o[l]=m,i.next(o)},h.next(u)):o[l]=u},h.complete=n,h.subscribe(d)};s.forEach(a)},"combineLatest",arguments)}function HE(...s){return we(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,d)=>{let l=new Te(i),h=[];r[d]=h,l.next=u=>{h.push(u),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Xn(...s){return i=>we((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var yu=class extends Te{constructor(i,...e){super(i);let t=new Te(this.sink);t.next=r=>this.buffer=r,t.complete=$e,t.subscribe(qp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},GE=Ae(yu,"withLatestFrom"),bu=class extends Te{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()}},WE=Ae(bu,"bufferCount"),vu=class extends Te{constructor(i,e){super(i),this.buffer=[];let t=new Te(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=$e,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},zE=Ae(vu,"buffer");var jE=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(h){try{l(t.next(h))}catch(u){n(u)}}function d(h){try{l(t.throw(h))}catch(u){n(u)}}function l(h){h.done?o(h.value):r(h.value).then(a,d)}l((t=t.apply(s,i||[])).next())})};function Vt(s){let i=arguments,e=Nr()(we(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=$e,e.complete=$e,e.error=$e,e}function Xp(s){return we(i=>i.subscribe(s()),"defer",arguments)}var Qp=s=>i=>{setTimeout(()=>s(i))},Yp=s=>Qp(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function JE(...s){return we(Yp(s),"of",arguments)}function qE(s){return we(Yp(s),"fromArray",arguments)}function ku(s){return we(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Qn(s,i){return we(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function Wd(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function XE(s,i){return we(Wd(s,i),"fromEventPattern",arguments)}function We(s,i){if("on"in s&&"off"in s)return we(Wd(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return we(Wd(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return we(Wd(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Zp(s){return we(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function QE(s,i){return we(Xp(()=>Zp(fetch(s,i))),"fromFetch",arguments)}function YE(s){return we(Qp(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function ZE(s){let i=e=>jE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return we(e=>{i(e)},"fromReader",arguments)}function KE(s){return we(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function eT(){return we(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function tT(s,i){return we((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function iT(s,i,...e){return we(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function rT(s,i,...e){return we(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function sT(){return we(()=>{},"never",arguments)}function oT(s){return we(i=>i.error(s),"throwError",arguments)}function Yn(){return we(s=>s.complete(),"empty",arguments)}var ws=class extends Te{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)}},Ou=Ae(ws,"reduce"),nT=s=>Ae(ws,"count")((i,e)=>s(e)?i+1:i,0),aT=()=>Ae(ws,"max")(Math.max),dT=()=>Ae(ws,"min")(Math.min),cT=()=>Ae(ws,"sum")((s,i)=>s+i,0);var wu=class extends Te{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Zi=Ae(wu,"filter"),Mu=class extends Te{next(i){}},lT=Ae(Mu,"ignoreElements"),xu=class extends Te{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Dr=Ae(xu,"take"),Lu=class extends Te{constructor(i,e){super(i);let t=new Te(i);t.next=()=>i.complete(),t.complete=Hd,t.subscribe(e)}},St=Ae(Lu,"takeUntil"),Pu=class extends Te{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Kp=Ae(Pu,"takeWhile"),uT=s=>Ou((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),Uu=class extends Te{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},hT=Ae(Uu,"skip"),Vu=class extends Te{constructor(i,e){super(i),i.next=$e;let t=new Te(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Hd,t.subscribe(e)}},mT=Ae(Vu,"skipUntil"),Bu=class extends Te{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Jd=Ae(Bu,"skipWhile"),pT={leading:!0,trailing:!1},$u=class extends Te{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)}},zd=class extends Te{constructor(i,e,t=pT){super(i),this.durationSelector=e,this.config=t,this._throttle=new $u(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=$e,this._throttle.complete(),super.complete()}},fT=Ae(zd,"throttle"),_T={leading:!1,trailing:!0},gT=s=>Ae(zd,"audit")(s,_T),Fu=class extends Te{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},jd=class extends Te{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Fu(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()}},ET=Ae(jd,"debounce"),TT=s=>Ae(jd,"debounceTime")(i=>Qn(s)),Hu=class extends Te{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()}},ST=Ae(Hu,"elementAt"),IT=s=>i=>Dr(1)(Jd(e=>!s(e))(i)),Gu=class extends Te{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}},AT=Ae(Gu,"findIndex"),Wu=class extends Te{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()}},CT=Ae(Wu,"first"),zu=class extends Te{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()}},RT=Ae(zu,"last"),ju=class extends Te{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()}},yT=Ae(ju,"every");var Ju=class extends Te{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))}},rh=Ae(Ju,"scan"),qu=class extends Te{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},bT=Ae(qu,"pairwise"),qd=class extends Te{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Zn=Ae(qd,"map"),vT=s=>Ae(qd,"mapTo")(i=>s),Co=class extends Te{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()}},Ro=class extends Te{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()}},Xd=class extends Co{},Qd=class extends Ro{next(i){this.subInner(i,Xd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Xd)}}},yo=Ae(Qd,"switchMap");function ec(s){return(i,e)=>s(()=>i,e)}var Ms=ec(Ae(Qd,"switchMapTo")),Xu=class extends Co{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Yd=class extends Ro{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(),Xu),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},NT=Ae(Yd,"concatMap"),DT=ec(Ae(Yd,"concatMapTo")),Qu=class extends Co{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Zd=class extends Ro{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Qu),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},kT=Ae(Zd,"mergeMap"),OT=ec(Ae(Zd,"mergeMapTo")),Yu=class extends Co{dispose(){this.context.resetNext(),super.dispose()}},Kd=class extends Ro{next(i){this.next=$e,this.subInner(i,Yu)}},wT=Ae(Kd,"exhaustMap"),MT=ec(Ae(Kd,"exhaustMapTo")),Zu=class extends Te{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=Vt(),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)}},xT=Ae(Zu,"groupBy"),Ku=class extends Te{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}},LT=Ae(Ku,"timeInterval"),eh=class extends Te{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()}},PT=Ae(eh,"bufferTime"),th=class extends Te{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)}},UT=Ae(th,"delay"),ih=class extends Te{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},sh=Ae(ih,"catchError");var VT=()=>s=>new Promise((i,e)=>{let t;new Os(s,r=>t=r,e,()=>i(t))}),BT=()=>s=>{let i;return new ReadableStream({start(e){i=new Os(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},it=(s=$e,i=$e,e=$e)=>t=>new Os(t,s,i,e),oh=class extends Te{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)}))}},ah=Ae(oh,"tap"),nh=class extends Te{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new qn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},$T=Ae(nh,"timeout"),FT=(s=1/0)=>i=>{if(i instanceof di){let e=we(t=>{let r=s,o=new Te(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,Ke.pipe(e),e}else return e=>{let t=s,r=new Te(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var Ki=class Ki extends vs{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;c(this,"tinyId");c(this,"isRemote",!0);c(this,"jitterBufferDelay",0);c(this,"availableState");c(this,"remotePublishState");c(this,"_triggerCheckDecodeSubject",Vt(We(this,Ki.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new ge(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new ge(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),He(Nu(We(this,ge.STATECHANGED),We(this.remotePublishState,ge.STATECHANGED)),Zn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),it(d=>{this.availableState.state!==(d?ge.ON:ge.OFF)&&(this.availableState.state=d?ge.ON:ge.OFF),this.updatePlayingState(d)}));let o=He(We(this.player,Ge.ERROR),Zi(d=>d.code===MediaError.MEDIA_ERR_DECODE)),n=He(Qn(5e3),Zi(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===S.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=He(Du(o,n),St(We(this,ge.INIT)));He(this._triggerCheckDecodeSubject,Zi(()=>!this.ignoreDecodeError),Ms(a),it(d=>{this.reportDecodeResult(!1,d)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ki.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===ge.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===S.AUDIO;Q[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(Q.addEnum({key:r?504701:514703,value:Rn()}),Me.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ts()||gr()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===S.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?ge.ON:ge.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};c(Ki,"STATE_SUBSCRIBE","subscribe"),J([Fd(5,1)],Ki.prototype,"waitHasMediaTrack",1),J([qe(ge.INIT,Ki.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),x.emit(B.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),zt(521716,!1)],Ki.prototype,"subscribe",1),J([qe(Ki.STATE_SUBSCRIBE,ge.INIT,{sync:!0,success(){this.log.info("unsubscribed"),x.emit(B.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ki.prototype,"unsubscribe",1);var bo=Ki;var Ci=class extends bo{constructor(e,t){super(e,t,1);c(this,"volume",0);c(this,"mediaType",1);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return bs.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var GT=[-1,-1,1,-1,-1,1,1,1],WT=[0,0,1,0,0,1,1,1];var Bt=class extends ge{constructor(e,t){super();this.context=e;c(this,"name");c(this,"input");c(this,"output");c(this,"texture");c(this,"ctx2d",null);c(this,"fbo");c(this,"width",0);c(this,"height",0);c(this,"x",0);c(this,"y",0);c(this,"program");c(this,"vertexShader");c(this,"fragmentShader");c(this,"totalFrames",0);c(this,"dropFrames",0);c(this,"matchInputSize",!0);c(this,"texCoordBuffer");c(this,"positionBuffer");c(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});c(this,"cost",0);c(this,"_canvas",null);c(this,"_image");c(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Dt){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&Xt!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(WT),this.positionBuffer=this.createBuffer(GT),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 X({code:H.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 mt&&this.render(e)||this.context instanceof Dt&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof mt){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var u;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:d}=this,l=Date.now(),h=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:h,name:a,cost:d},Z({parent:(u=this.input)==null?void 0:u.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};J([qe(ge.INIT,"connected",{sync:!0})],Bt.prototype,"connect",1),J([qe("connected",ge.INIT,{ignoreError:!0,sync:!0})],Bt.prototype,"disconnect",1),J([qe([],"closed",{sync:!0})],Bt.prototype,"close",1);var zT=He(ku(250),Zn(()=>performance.now()),Nr());var tf=s=>i=>{let e=performance.now();He(zT,Jd(t=>t-e<s),Dr(1))(i)};var JT=[0,1,1,1,0,0,1,0],xs=class extends Bt{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));c(this,"_intervalId",0);c(this,"_sequence",0);c(this,"checkGLError",!1);c(this,"checkVisibilityChange");e instanceof Dt?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(JT)}start(e){this.log.info(`${this.name} start render ${e} fps`),Le.clearTask(this._intervalId),this._intervalId=Le.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Le.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof mt){let r=this.context.ctx.getError();r&&this.context.destroy(new X({code:H.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(Le.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),Le.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),Le.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},vo=class extends xs{constructor(e,t){super(e,t);c(this,"_videoTrack");c(this,"_muteOb");c(this,"_closedOb",We(this,"closed"));c(this,"_subscription");c(this,"_canvasContainer");Number(fr)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=We(this._videoTrack,"mute"),He(We(this._videoTrack,"ended"),St(this._closedOb),it(()=>{this.context.destroy(new X({code:H.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=He(this._muteOb,St(this._closedOb),Ms(tf(5e3)),Zi(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),it(()=>{this.context.destroy(new X({code:H.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()}},tc=class extends vo{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var ic=class extends vo{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 Kn=class extends Bt{constructor(e,t){super(e,Z({name:"imageSource"},t));c(this,"_lastImage");c(this,"_totalFrames",0);c(this,"_autoResize",!1);c(this,"_canvasRendered");c(this,"_videoCallbackId",0);c(this,"waitingFirstFrame",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,Xt===16&&(this._canvasRendered=Vt(),He(this._canvasRendered,Xn(this._image),yo(r=>r instanceof HTMLCanvasElement?We(r,"rendered"):Yn()),St(We(this,"closed")),it(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),ys()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let d=this.context.ctx;d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let d=this.context.ctx;d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},ea=class extends Kn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",He(We(this._player,Ge.PLAYER_STATE_CHANGED),St(We(this,"closed")),Zi(({state:o})=>o==="PLAYING"),it(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},kr=class extends ea{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new Zt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var XT=`
34
35
  // \u9876\u70B9\u7740\u8272\u5668
35
36
  attribute vec4 a_position;
36
37
  attribute vec2 a_texCoord;
@@ -40,7 +41,7 @@ void main() {
40
41
  gl_Position = a_position;
41
42
  v_texCoord = a_texCoord;
42
43
  }
43
- `,_T=`
44
+ `,QT=`
44
45
  // \u7247\u5143\u7740\u8272\u5668
45
46
  precision mediump float;
46
47
  varying vec2 v_texCoord;
@@ -48,32 +49,43 @@ uniform sampler2D u_texture;
48
49
 
49
50
  void main() {
50
51
  gl_FragColor = texture2D(u_texture, v_texCoord);
51
- } `;var Br=class extends ${constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Vi(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Os(this,e)}createVideoImageSource(e,t){return new zo(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Qo(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Br,"_ids",0);var gT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ks=class ks extends Br{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Br._ids++}`),this.ctx=this._canvas.getContext("webgl2",gT),!this.ctx)throw new y({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,fT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,_T),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(ks,"UNAVAILABLE","unavailable"),N([_e($.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],ks.prototype,"create",1),N([_e("created",$.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(ks.UNAVAILABLE,e),this.removeAllListeners()}})],ks.prototype,"destroy",1);var Oe=ks,je=class extends Br{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Br._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,b.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(),b.addSuccessEvent({key:512703})}};N([_e($.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],je.prototype,"create",1),N([_e("created",$.INIT,{ignoreError:!0,sync:!0})],je.prototype,"destroy",1);function TT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var ui=class extends Ds{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:lt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new je({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Vr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Nr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=TT(t);if(!J(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Ms=class extends ui{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ls=new Map;E.on(I.JOIN_SUCCESS,({room:s})=>{Ee(s.userId,{eventId:32788})});E.on(I.LEAVE_START,({room:s})=>{Ee(s.userId,{eventId:32789})});E.on(I.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ee(s.room.userId,{eventId:i})}});E.on(I.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ee(s.room.userId,{eventId:i})}});E.on(I.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===h.AUDIO?Ee(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ee(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(I.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===h.AUDIO?Ee(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ee(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(I.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ee(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ee(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ee(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(I.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ee(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ee(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ee(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(I.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ee(s.room.userId,{eventId:s.kind===h.VIDEO?32780:32781})});E.on(I.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ee(s.room.userId,{eventId:s.kind===h.VIDEO?32782:32783})});E.on(I.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ee(s.userId,{eventId:t})});E.on(I.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ee(s.userId,{eventId:o,remoteUserId:t})});E.on(I.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ee(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(I.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)),Ee(s.userId,e)}});function Ee(s,i){let e=w(v({},i),{timestamp:qs()});Ls.has(s)?Ls.get(s).push(e):Ls.set(s,[e])}function Dh(s){if(Ls.has(s)){let i=Ls.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 Ls.delete(s),i}return[]}function Oh(...s){return z((i,e)=>function(...t){return ET.call(this,s,t,e,this._name),i.apply(this,t)})}function ET(s,i,e,t){try{if(Te(s))for(let r=0;r<s.length;r++)Xa.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Xa.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function Xa({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),K(s.type[c])&&Se(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>Er(c)?Zr(c):K(c)?c:Se(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Se(i)!==s.type)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=J(i)&&(i===0||Number.isNaN(i)),c=K(i)&&i.trim()==="";if(a||c)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&J(i)&&i<0)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&J(i)&&i<s.min)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&J(i)&&i>s.max)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;He(o)&&bt(i)&&Object.keys(o).forEach(a=>{Xa.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;He(n)&&Te(i)&&i.forEach((a,c)=>{Xa.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var kh=Be(Qe(),1);var za=class extends kh.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Wc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=Si(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){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:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Si(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function ql({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return z((t,r)=>{let o=new WeakMap;return E.on(I.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new y({code:S.INVALID_OPERATION,message:P({key:L.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var ST="2025-06-04 15:58:04",Mh=!0,Lh=function(){var s;if(Mh){Mh=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ht}/en/index.html`),console.info(`* Changelog: ${Ht}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",ke),Lt||C.debug("Build Time:",ST);let i=`UA: ${navigator.userAgent}
52
- CPU core: ${navigator.hardwareConcurrency}, GPU: ${fd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Eo().then(t=>{t&&C.info(Dt)})}};var It={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var F={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Ut=(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.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(Ut||{});function wh({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Ut[s];try{r=Ph[o]}catch(n){r=Ph.UNKNOWN_ERROR}return ne(r)?t=r(i):K(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Ph=w(v({},we),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Se(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: ${Se(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=Fr(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=Fr(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=Fr(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=Fr(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=Fr(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=Fr(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=Fr(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 Fr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Xl=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=wh({code:e===F.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=Ut[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},f=document.createElement("a");Ir?f.href=`ms-settings:privacy-${m[this.functionName]}`:Mt&&(f.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),f.href.length>0&&f.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof y){let{stack:n}=e,a={code:F.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=F.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=F.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=F.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(we.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=F.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=F.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=IT(e.name));break;case S.UNKNOWN:break;default:a.code=F.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
53
- `)))}else{if(e instanceof s)return e;o=new s({code:F.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function IT(s){let i;switch(s){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var B=Xl;function or(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function Yo(s){return s===It.QOS_PREFERENCE_CLEAR?"detail":s===It.QOS_PREFERENCE_SMOOTH?"motion":""}function Ps(s,i){let e=i?xc:ji;return Kc(s)?v(v({},e),s):Rt[s]?Rt[s]:e}var xh={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Uh={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}}},ws={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(K(s)&&!document.getElementById(s))throw new B({code:F.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Vh={name:"userId",required:!0,type:"string"},Bh={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[It.AUDIO_PROFILE_STANDARD,It.AUDIO_PROFILE_STANDARD_STEREO,It.AUDIO_PROFILE_HIGH,It.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Zo(s,i){if(!s)throw new B({code:F.INVALID_OPERATION,extraCode:5101,fnName:i})}function Fh(s,i,e){if(!s)throw new B({code:F.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var CO={type:"number",notLessThanZero:!0},AT=(s,i)=>s.width*s.height>=i.width*i.height&&s.frameRate>=i.frameRate&&s.bitrate>=i.bitrate;function $h(s){var t;if(!((t=s==null?void 0:s.option)!=null&&t.small))return;if(!ua()){C.warn("small stream is not supported"),delete s.option.small;return}let i=Ps(s.option.profile),e=Ps(s.option.small,!0);if(!AT(i,e)){C.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete s.option.small;return}}var CT={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new B({code:F.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(K(s.roomId))throw new B({code:F.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new B({code:F.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new B({code:F.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new B({code:F.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:ws,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:xh},validate(s){var i,e;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Di())throw new B({code:F.ENV_NOT_SUPPORTED,extraCode:5201});(e=s==null?void 0:s.option)!=null&&e.small&&$h(s)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(v({},ws),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:xh},validate(s){var i;(i=s==null?void 0:s.option)!=null&&i.small&&$h(s)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Bh},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Di())throw new B({code:F.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Bh}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ws,publish:{type:"boolean"},option:Uh},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(Di())throw new B({code:F.ENV_NOT_SUPPORTED,extraCode:5201});if(!No())throw new B({code:F.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ws,publish:{type:"boolean"},option:Uh}},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:ws,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){Zo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Fh(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new B({code:F.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(v({},ws),{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){Zo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Fh(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new B({code:F.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!=="*"&&T(s.streamType))throw new B({code:F.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Zo(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(!ko)throw new B({code:F.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new B({code:F.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new B({code:F.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new B({code:F.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Zo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new B({code:F.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new B({code:F.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new B({code:F.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Zo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new B({code:F.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ue={TRTC:CT};var qe=class extends Error{};function RT(s,i){let e=_r(s);for(let t=0;t<i.length;t++)Wt(e[t],i[t]);return e}function yT(s){this._resolve=Promise.resolve(s)}function bT(s){this._reject=Promise.reject(s)}var nr=class nr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",RT);let t=nr.instances.get(i);t?t.set(e,this):nr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=nr.instances.get(i);return t&&t.get(e)||new nr(i,e)}static gets(i,e){let t=nr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new qe("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:yT,reject:bT};try{switch(this.state){case 1:if(i===0)throw new qe("already started");break;case 4:if(i===2)throw new qe("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new qe("already start");break;case 3:switch(i.type){case 2:throw new qe("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new qe("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new qe("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new qe("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new qe("start not allowed after update");case 0:throw new qe("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new qe("keep start")),new qe("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(nr,"instances",new WeakMap);var Bi=nr;var Qa=new WeakMap,Ya=(s,i)=>{if(i instanceof qe){let{stack:e}=i;i=new B({code:F.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
54
- `)))}throw i};function ar(s,i){return z((e,t)=>function(...r){let o=Bi.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(Ya.bind(null,t))):e.apply(this,r)})}function $r(s,i){let{merge:e,debounce:t}=i||{};return z((r,o)=>function(...n){let a=Bi.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:l}=t;return new Promise((u,m)=>{var D,_;let f=(D=Qa.get(this))==null?void 0:D.get(l(...n));if(f){let{timeoutId:A,resolve:O}=f;clearTimeout(A),O()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(Ya.bind(null,o)).then(u,m)},c);Qa.has(this)?(_=Qa.get(this))==null||_.set(l(...n),{timeoutId:g,resolve:u}):Qa.set(this,new Map([[l(...n),{timeoutId:g,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(Ya.bind(null,o))})}function cr(s){return z((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(Bi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Bi.get(this,r);return o?o.action(3,i.bind(this),t).catch(Ya.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",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},Hh=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,M.FIRST_VIDEO_FRAME]);var Ql={};fi(Ql,{bytes2ms:()=>Zu,calculateScaleResolutionDownNumber:()=>rs,convertObjectNumberToInt:()=>oo,copyProperties:()=>Yu,deepClone:()=>_r,deepMerge:()=>Wt,delay:()=>Ii,fibonacci:()=>Tr,formatedTime:()=>nm,getConstructorName:()=>Zr,getContainerFromElement:()=>om,getEnv:()=>zu,getInternalVersion:()=>rm,getLoggerUrl:()=>Ei,getMediaStreamTrackInfo:()=>Ln,getMuteStateFromFlag:()=>Si,getNetworkType:()=>jc,getNumNetworkType:()=>gr,getReconnectionTimeout:()=>Nt,getStringByteLength:()=>so,getTurnServer:()=>sm,getUint32Version:()=>On,getValueType:()=>Se,getViewListFromView:()=>ts,glog:()=>zc,ipv4ToUint32:()=>es,isArray:()=>Te,isAudioWorkletSupported:()=>im,isBoolean:()=>he,isConstructor:()=>Er,isEmpty:()=>Kr,isFunction:()=>ne,isLangChinese:()=>vt,isMediaStreamTrack:()=>em,isNumber:()=>J,isObject:()=>bt,isOverseaSdkAppId:()=>ro,isPlainObject:()=>He,isPortrait:()=>Qc,isPromise:()=>Qi,isRemoteTrack:()=>tm,isString:()=>K,isUndefined:()=>T,loadImage:()=>is,ms2bytes:()=>Ku,ms2samples:()=>Xc,normalizeUrl:()=>Mn,performanceNow:()=>x,promiseAny:()=>Sr,samples2ms:()=>qc,setNetworkType:()=>Nn,stringify:()=>gt,stringifyIncludeValue:()=>Dn,throttlePromise:()=>kn});var Kl={};fi(Kl,{ScheduleRequestType:()=>Wh,getAbilityConfig:()=>NT,getScheduleDomain:()=>Jh,isNeedToSchedule:()=>Za,scheduleProxy:()=>lr,sendScheduleRequest:()=>Zl,setIsNeedToSchedule:()=>Vt,setScheduleProxy:()=>Ka});var Yl=null,Za=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ti).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
55
- `));function Vt(s){he(s)&&s!==Za&&(Za=s,C.info(`setIsNeedToSchedule ${s}`))}E.on("28",()=>Vt(!0));E.on("63",()=>Vt(!0));E.on("84",()=>Vt(!0));E.on("201",s=>{s.state==="RECONNECTING"&&Vt(!0)});E.on("202",s=>{s.state==="RECONNECTING"&&Vt(!0)});function vT(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=dr(s,"config",h.MAIN),n=dr(s,"config",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,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,f=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,g=Math.round(a.domainLookupEnd-a.domainLookupStart),D=Math.round(a.requestStart-a.secureConnectionStart),_=Math.round(a.secureConnectionStart-a.connectStart),A=Math.round(a.responseStart-a.requestStart),O=Math.round(a.responseEnd-a.responseStart),re=[g,D,_,A,O];ie.uploadEvent({log:`stat-schedule-net:${l}(${u}(${m}->${f})->${re.join("->")}) ${c}`,userId:i}),t=w(v({},t),{totalCost:l,local:u,dns:g,tcp:_,tls:D,request:A,response:O});break}}catch(r){C.error("getScheduleDetailCost error",r)}return t}function Zl(l){return p(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!Za&&Yl)return{isCached:!0,result:Yl};let u={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 f=x(),g=yield OT(m,u,i);g.config&&(g.config.loggerDomain&&ur(g.config.loggerDomain),he(g.config.scheduleCache)&&Vt(!g.config.scheduleCache)),u.delta=x()-f;let D=vT(Number(i),s,f);return Yl=g,{isCached:!1,result:g,detailCost:D}}catch(m){let f=Te(m)?m[0]:m,g=J(f.code)?f.code:0,D=`schedule failed${f.message?`: ${f.message}`:""}`,_=new y({code:S.SCHEDULE_FAILED,extraCode:g,message:P({key:L.JOIN_ROOM_FAILED,data:{error:D,code:g}})});throw C.error(D,g),_}})}var lr={main:"",backup:""};function Ka(s){Te(s)?(lr.main=s[0],lr.backup=s[1]):lr.main=s}var Wh=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Wh||{});function dr(s,i,e=h.MAIN,t=!1){return`https://${lr[e]||Jh(s,e,t)}/api/v1/${i}`}function NT(s,i,e){let t=dr(s,i),r=dr(s,i,h.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(c=>c.json()),a=fetch(`${r}?${o}`).then(c=>c.json());return Sr([n,a])}function Jh(s,i=h.MAIN,e=!1){let t;return ro(s)?e?t=i===h.MAIN?Ti.MAIN_OVERSEA_BACKUP:Ti.BACKUP_OVERSEA:t=i===h.MAIN?Ti.MAIN_OVERSEA:Ti.BACKUP_OVERSEA:t=i===h.MAIN?Ti.MAIN:Ti.BACKUP,t}function DT(s,i,e){return new Promise((t,r)=>{Ai({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var Gh=(s,i)=>jt({retryFunction:DT,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function OT(s,i,e){return new Promise((t,r)=>{let o=null;Sr([Gh(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(c>=1&&(l[0]=dr(e,"config",h.MAIN,!0)),a())})(dr(e,"config",h.MAIN),s,{get timeout(){return Tr(2+i.count[0])*1e3}}),Gh(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(c>=2&&(l[0]=dr(e,"config",h.BACKUP,!0)),a())})(dr(e,"config",h.BACKUP),s,{get timeout(){return Tr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var kT=s=>s.startsWith("data:application/octet-stream;base64,"),MT=s=>s.startsWith("file://"),Ko=class{constructor(){d(this,"_log");this._log=C.createLogger({id:"fd"})}download(i,e){return p(this,null,function*(){let{type:t="blob"}=e||{};i=Mn(i);try{let r=x(),o;if(ne(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=x()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),b.addSuccessEvent({key:522700,cost:x()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),b.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return p(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)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 p(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),r=null,o=null;if(ne(WebAssembly.instantiateStreaming)&&!kT(i)&&!MT(i)&&ne(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=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),b.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),b.addFailedEvent({key:522701,error:o}),o})}loadScript(i){this._log.info(`loadScript ${i}`);let e=x();return new Promise((t,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${x()-e}ms`),b.addSuccessEvent({key:522702,cost:x()-e,split:1e3}),t(o)},o.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${n}`),b.addFailedEvent({key:522702}),r(n)},o.crossOrigin="anonymous",o.src=i,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};N([ht({settings:{timeout:0,retries:3},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Ko.prototype,"download",1),N([ht({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],Ko.prototype,"loadScript",1);var jh=new Ko;function qh({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:jh,innerEmitter:E,constants:Jc,environment:fs,utils:Ql,eventLogger:ie,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:b,rtcDectection:ti,trtc:this,rx:Jl,enums:Od,schedule:Kl,clearStarted:(r,o)=>{let n=r.getAlias(),a=Bi.instances.get(this);if(a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Go,createAudioNode:tl}}var Xh=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=P({key:L.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
52
+ } `;var Ls=class extends ge{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new kr(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new vo(this,e)}createVideoImageSource(e,t){return new Kn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new ea(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(Ls,"_ids",0);var YT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},No=class No extends Ls{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ls._ids++}`),this.ctx=this._canvas.getContext("webgl2",YT),!this.ctx)throw new X({code:H.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,XT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,QT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new X({code:H.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,Q.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};c(No,"UNAVAILABLE","unavailable"),J([qe(ge.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),Q.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),Q.addSuccessEvent({key:512700})}})],No.prototype,"create",1),J([qe("created",ge.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(No.UNAVAILABLE,e),this.removeAllListeners()}})],No.prototype,"destroy",1);var mt=No,Dt=class extends Ls{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ls._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new X({code:H.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,Q.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(),Q.addSuccessEvent({key:512703})}};J([qe(ge.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),Q.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),Q.addSuccessEvent({key:512701})}})],Dt.prototype,"create",1),J([qe("created",ge.INIT,{ignoreError:!0,sync:!0})],Dt.prototype,"destroy",1);function ZT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var er=class extends bo{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(Qe(t==null?void 0:t.canvasRender)?t.canvasRender:Xt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Dt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new xs(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),ys()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=ZT(t);if(!De(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Do=class extends er{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ko=new Map;x.on(B.JOIN_SUCCESS,({room:s})=>{Ze(s.userId,{eventId:32788})});x.on(B.LEAVE_START,({room:s})=>{Ze(s.userId,{eventId:32789})});x.on(B.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ze(s.room.userId,{eventId:i})}});x.on(B.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ze(s.room.userId,{eventId:i})}});x.on(B.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===S.AUDIO?Ze(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ze(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});x.on(B.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===S.AUDIO?Ze(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ze(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});x.on(B.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ze(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ze(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ze(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});x.on(B.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ze(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ze(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ze(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});x.on(B.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ze(s.room.userId,{eventId:s.kind===S.VIDEO?32780:32781})});x.on(B.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ze(s.room.userId,{eventId:s.kind===S.VIDEO?32782:32783})});x.on(B.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&&Ze(s.userId,{eventId:t})});x.on(B.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&&Ze(s.userId,{eventId:o,remoteUserId:t})});x.on(B.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let d=t==="h264"?0:2,l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ze(i,l),Q.addEnum({key:e?514701:513701,value:a}),Q.addEnum({key:e?514700:513700,value:d})});x.on(B.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===S.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ze(s.userId,e)}});function Ze(s,i){let e=de(Z({},i),{timestamp:Zo()});ko.has(s)?ko.get(s).push(e):ko.set(s,[e])}function rf(s){if(ko.has(s)){let i=ko.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 ko.delete(s),i}return[]}var sf=gt(Mt(),1);var rc=class extends sf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;M(t)||(o+=`:${cl[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,d=ur(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState: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:ur(0,n),muteState:d,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function lh({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return be((t,r)=>{let o=new WeakMap;return x.on(B.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 X({code:H.INVALID_OPERATION,message:pe({key:me.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 KT="2025-06-06 15:06:22",of=!0,nf=function(){var s;if(of){of=!1,z.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${wi}/en/index.html`),console.info(`* Changelog: ${wi}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),z.info("TRTC Web SDK Version:",Rt),Ti||z.debug("Build Time:",KT);let i=`UA: ${navigator.userAgent}
53
+ CPU core: ${navigator.hardwareConcurrency}, GPU: ${wl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),z.info(i),z.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Es().then(t=>{t&&z.info(fi)})}};var ci={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var fe={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},Ri=(U=>(U[U.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",U[U.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",U[U.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",U[U.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",U[U.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",U[U.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",U[U.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",U[U.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",U[U.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",U[U.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",U[U.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",U[U.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",U[U.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",U[U.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",U[U.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",U[U.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",U[U.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",U[U.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",U[U.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",U[U.INVALID_OPERATION=5100]="INVALID_OPERATION",U[U.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",U[U.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",U[U.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",U[U.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",U[U.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",U[U.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",U[U.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",U[U.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",U[U.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",U[U.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",U[U.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",U[U.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",U[U.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",U[U.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",U[U.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",U[U.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",U[U.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",U[U.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",U[U.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",U[U.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",U[U.DEVICE_ERROR=5300]="DEVICE_ERROR",U[U.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",U[U.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",U[U.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",U[U.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",U[U.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",U[U.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",U[U.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",U[U.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",U[U.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",U[U.SERVER_ERROR=5400]="SERVER_ERROR",U[U.NEED_TO_BUY=5401]="NEED_TO_BUY",U[U.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",U[U.OPERATION_FAILED=5500]="OPERATION_FAILED",U[U.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",U[U.REJOIN_FAILED=5502]="REJOIN_FAILED",U[U.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",U[U.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",U[U.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",U[U.OPERATION_ABORT=5998]="OPERATION_ABORT",U[U.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",U))(Ri||{});function df({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Ri[s];try{r=af[o]}catch(n){r=af.UNKNOWN_ERROR}return Fe(r)?t=r(i):Oe(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var af=de(Z({},Tt),{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: ${lt(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: ${lt(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=Ps(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=Ps(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=Ps(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=Ps(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=Ps(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=Ps(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=Ps(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 Ps(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var uh=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let d;r?d=r:d=df({code:e===fe.SERVER_ERROR?e:t||e,params:Z({fnName:n,error:a},o)});super(d);c(this,"name","RtcError");c(this,"code");c(this,"extraCode");c(this,"functionName");c(this,"message");c(this,"handler");c(this,"originError");this.name=Ri[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=d,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");gs?m.href=`ms-settings:privacy-${u[this.functionName]}`:Ei&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof X){let{stack:n}=e,a={code:fe.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case H.INVALID_PARAMETER:a.code=fe.INVALID_PARAMETER,a.message=e.message;break;case H.INVALID_OPERATION:a.code=fe.INVALID_OPERATION;break;case H.NOT_SUPPORTED:case H.NOT_SUPPORTED_H264:a.code=fe.ENV_NOT_SUPPORTED,e.getCode()===H.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Tt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case H.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case H.SERVER_TIMEOUT:case H.SWITCH_ROLE_FAILED:a.code=fe.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case H.API_CALL_ABORTED:a.code=fe.OPERATION_ABORT;break;case H.DEVICE_NOT_FOUND:case H.DEVICE_AUTO_RECOVER_FAILED:case H.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=eS(e.name));break;case H.UNKNOWN:break;default:a.code=fe.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
54
+ `)))}else{if(e instanceof s)return e;o=new s({code:fe.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function eS(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 ue=uh;var cf={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}}},lf={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}}},Oo={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(Oe(s)&&!document.getElementById(s))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},uf={name:"userId",required:!0,type:"string"},hf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ci.AUDIO_PROFILE_STANDARD,ci.AUDIO_PROFILE_STANDARD_STEREO,ci.AUDIO_PROFILE_HIGH,ci.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function ta(s,i){if(!s)throw new ue({code:fe.INVALID_OPERATION,extraCode:5101,fnName:i})}function mf(s,i,e){if(!s)throw new ue({code:fe.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var t0={type:"number",notLessThanZero:!0},tS={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 ue({code:fe.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(Oe(s.roomId))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new ue({code:fe.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 ue({code:fe.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new ue({code:fe.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Oo,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:cf},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Ir())throw new ue({code:fe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:de(Z({},Oo),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:cf}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:hf},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Ir())throw new ue({code:fe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:hf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Oo,publish:{type:"boolean"},option:lf},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(Ir())throw new ue({code:fe.ENV_NOT_SUPPORTED,extraCode:5201});if(!kn())throw new ue({code:fe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Oo,publish:{type:"boolean"},option:lf}},muteRemoteAudio:[uf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[uf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Oo,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){ta(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(mf(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new ue({code:fe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:de(Z({},Oo),{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){ta(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(mf(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new ue({code:fe.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!=="*"&&M(s.streamType))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){ta(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(!xn)throw new ue({code:fe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ue({code:fe.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});ta(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 ue({code:fe.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 ue({code:fe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(ta(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ue({code:fe.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},It={TRTC:tS};var kt=class extends Error{};function iS(s,i){let e=hs(s);for(let t=0;t<i.length;t++)Li(e[t],i[t]);return e}function rS(s){this._resolve=Promise.resolve(s)}function sS(s){this._reject=Promise.reject(s)}var Kr=class Kr{constructor(i,e){this.instance=i;this.group=e;c(this,"started",!1);c(this,"ops",[]);c(this,"startSame",()=>!0);c(this,"mergeUpdate",iS);let t=Kr.instances.get(i);t?t.set(e,this):Kr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Kr.instances.get(i);return t&&t.get(e)||new Kr(i,e)}static gets(i,e){let t=Kr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},o=a=>{var d,l;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new kt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:rS,reject:sS};try{switch(this.state){case 1:if(i===0)throw new kt("already started");break;case 4:if(i===2)throw new kt("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 kt("already start");break;case 3:switch(i.type){case 2:throw new kt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new kt("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new kt("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 kt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new kt("start not allowed after update");case 0:throw new kt("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new kt("keep start")),new kt("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};c(Kr,"instances",new WeakMap);var Or=Kr;var sc=new WeakMap,oc=(s,i)=>{if(i instanceof kt){let{stack:e}=i;i=new ue({code:fe.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
55
+ `)))}throw i};function es(s,i){return be((e,t)=>function(...r){let o=Or.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(oc.bind(null,t))):e.apply(this,r)})}function Us(s,i){let{merge:e,debounce:t}=i||{};return be((r,o)=>function(...n){let a=Or.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=t;return new Promise((h,u)=>{var g,f;let m=(g=sc.get(this))==null?void 0:g.get(l(...n));if(m){let{timeoutId:T,resolve:I}=m;clearTimeout(T),I()}let p=setTimeout(()=>{if(a.state===3||a.state===4)return h();a.action(2,r.bind(this),n).catch(oc.bind(null,o)).then(h,u)},d);sc.has(this)?(f=sc.get(this))==null||f.set(l(...n),{timeoutId:p,resolve:h}):sc.set(this,new Map([[l(...n),{timeoutId:p,resolve:h}]]))})}return a.action(2,r.bind(this),n).catch(oc.bind(null,o))})}function ts(s){return be((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(Or.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Or.get(this,r);return o?o.action(3,i.bind(this),t).catch(oc.bind(null,e)):i.apply(this,t)})}var ne={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},pf=new Set([ne.ERROR,ne.AUTOPLAY_FAILED,ne.KICKED_OUT,ne.REMOTE_USER_ENTER,ne.REMOTE_USER_EXIT,ne.REMOTE_AUDIO_AVAILABLE,ne.REMOTE_AUDIO_UNAVAILABLE,ne.REMOTE_VIDEO_AVAILABLE,ne.REMOTE_VIDEO_UNAVAILABLE,ne.CONNECTION_STATE_CHANGED,ne.PUBLISH_STATE_CHANGED,ne.SCREEN_SHARE_STOPPED,ne.DEVICE_CHANGED,ne.FIRST_VIDEO_FRAME]);function is(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function ia(s){return s===ci.QOS_PREFERENCE_CLEAR?"detail":s===ci.QOS_PREFERENCE_SMOOTH?"motion":""}var mh={};nr(mh,{bytes2ms:()=>ym,convertObjectNumberToInt:()=>un,copyProperties:()=>Rm,deepClone:()=>hs,deepMerge:()=>Li,delay:()=>hr,fibonacci:()=>fs,formatedTime:()=>Mm,getConstructorName:()=>cn,getContainerFromElement:()=>wm,getEnv:()=>Am,getInternalVersion:()=>km,getLoggerUrl:()=>lr,getMediaStreamTrackInfo:()=>Ha,getMuteStateFromFlag:()=>ur,getNetworkType:()=>ul,getNumNetworkType:()=>ps,getReconnectionTimeout:()=>pi,getStringByteLength:()=>ln,getTurnServer:()=>Om,getUint32Version:()=>Ba,getValueType:()=>lt,getViewListFromView:()=>Ks,glog:()=>pl,ipv4ToUint32:()=>Zs,isArray:()=>tt,isAudioWorkletSupported:()=>Dm,isBoolean:()=>Qe,isConstructor:()=>Qs,isEmpty:()=>Ys,isFunction:()=>Fe,isLangChinese:()=>mi,isMediaStreamTrack:()=>vm,isNumber:()=>De,isObject:()=>xi,isOverseaSdkAppId:()=>ms,isPlainObject:()=>Ht,isPortrait:()=>Va,isPromise:()=>Wr,isRemoteTrack:()=>Nm,isString:()=>Oe,isUndefined:()=>M,loadImage:()=>eo,ms2bytes:()=>bm,ms2samples:()=>ml,normalizeUrl:()=>Fa,performanceNow:()=>le,promiseAny:()=>_s,samples2ms:()=>hl,setNetworkType:()=>Pa,stringify:()=>oi,stringifyIncludeValue:()=>Ua,throttlePromise:()=>$a});var _h={};nr(_h,{ScheduleRequestType:()=>_f,getAbilityConfig:()=>nS,getScheduleDomain:()=>dc,isNeedToSchedule:()=>nc,scheduleProxy:()=>tr,sendScheduleRequest:()=>fh,setIsNeedToSchedule:()=>yi,setScheduleProxy:()=>ac});var ph=null,nc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(cr).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
56
+ `));function yi(s){Qe(s)&&s!==nc&&(nc=s,z.info(`setIsNeedToSchedule ${s}`))}x.on("28",()=>yi(!0));x.on("63",()=>yi(!0));x.on("84",()=>yi(!0));x.on("201",s=>{s.state==="RECONNECTING"&&yi(!0)});x.on("202",s=>{s.state==="RECONNECTING"&&yi(!0)});function oS(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=rs(s,"config",S.MAIN),n=rs(s,"config",S.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let d=a.name===o?S.MAIN:S.BACKUP,l=Math.round(a.duration),h=Math.round(a.domainLookupStart-a.startTime),u=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,p=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),f=Math.round(a.secureConnectionStart-a.connectStart),T=Math.round(a.responseStart-a.requestStart),I=Math.round(a.responseEnd-a.responseStart),v=[p,g,f,T,I];Me.uploadEvent({log:`stat-schedule-net:${l}(${h}(${u}->${m})->${v.join("->")}) ${d}`,userId:i}),t=de(Z({},t),{totalCost:l,local:h,dns:p,tcp:f,tls:g,request:T,response:I});break}}catch(r){z.error("getScheduleDetailCost error",r)}return t}function fh(l){return A(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:d}){if(!nc&&ph)return{isCached:!0,result:ph};let h={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(s)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(e)),u.append("groupId",String(t)),u.append("sdkVersion",o),u.append("userSig",String(r));let m=yield Es();m!=null&&m.model&&u.append("model",String(m==null?void 0:m.model)),a&&u.append("role",String(a)),d&&u.append("latencyLevel",String(d)),n&&u.append("frameWorkType",String(n));let p=le(),g=yield dS(u,h,i);g.config&&(g.config.loggerDomain&&as(g.config.loggerDomain),Qe(g.config.scheduleCache)&&yi(!g.config.scheduleCache)),h.delta=le()-p;let f=oS(Number(i),s,p);return ph=g,{isCached:!1,result:g,detailCost:f}}catch(u){let m=tt(u)?u[0]:u,p=De(m.code)?m.code:0,g=`schedule failed${m.message?`: ${m.message}`:""}`,f=new X({code:H.SCHEDULE_FAILED,extraCode:p,message:pe({key:me.JOIN_ROOM_FAILED,data:{error:g,code:p}})});throw z.error(g,p),f}})}var tr={main:"",backup:""};function ac(s){tt(s)?(tr.main=s[0],tr.backup=s[1]):tr.main=s}var _f=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(_f||{});function rs(s,i,e=S.MAIN,t=!1){return`https://${tr[e]||dc(s,e,t)}/api/v1/${i}`}function nS(s,i,e){let t=rs(s,i),r=rs(s,i,S.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(d=>d.json()),a=fetch(`${r}?${o}`).then(d=>d.json());return _s([n,a])}function dc(s,i=S.MAIN,e=!1){let t;return ms(s)?e?t=i===S.MAIN?cr.MAIN_OVERSEA_BACKUP:cr.BACKUP_OVERSEA:t=i===S.MAIN?cr.MAIN_OVERSEA:cr.BACKUP_OVERSEA:t=i===S.MAIN?cr.MAIN:cr.BACKUP,t}function aS(s,i,e){return new Promise((t,r)=>{mr({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var ff=(s,i)=>Ui({retryFunction:aS,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function dS(s,i,e){return new Promise((t,r)=>{let o=null;_s([ff(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(d>=1&&(l[0]=rs(e,"config",S.MAIN,!0)),a())})(rs(e,"config",S.MAIN),s,{get timeout(){return fs(2+i.count[0])*1e3}}),ff(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(d>=2&&(l[0]=rs(e,"config",S.BACKUP,!0)),a())})(rs(e,"config",S.BACKUP),s,{get timeout(){return fs(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var cS=s=>s.startsWith("data:application/octet-stream;base64,"),lS=s=>s.startsWith("file://"),cc=class{constructor(){c(this,"_log");this._log=z.createLogger({id:"fd"})}download(i,e){return A(this,null,function*(){let{type:t="blob"}=e||{};i=Fa(i);try{let r=le(),o;if(Fe(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=le()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),Q.addSuccessEvent({key:522700,cost:le()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),Q.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return A(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 A(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=le(),r=null,o=null;if(Fe(WebAssembly.instantiateStreaming)&&!cS(i)&&!lS(i)&&Fe(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=le()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),Q.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),Q.addFailedEvent({key:522701,error:o}),o})}};J([Gt({settings:{timeout:0,retries:3},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],cc.prototype,"download",1);var gf=new cc;function Ef({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:gf,innerEmitter:x,constants:ll,environment:mo,utils:mh,eventLogger:Me,log:this.room.getLogger(),loggerManager:z,errorModule:e,kvStatManager:Q,rtcDectection:Wi,trtc:this,rx:dh,enums:Jl,schedule:_h,clearStarted:(r,o)=>{let n=r.getAlias(),a=Or.instances.get(this);if(a)if(o){let d=a.get(n+o);if(!d)return;d.started=!1}else a.forEach((d,l)=>{l.startsWith(n)&&(d.started=!1)})},startGetPCM:Jn,createAudioNode:Gn}}var Tf=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=pe({key:me.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return z.warn(`${o}
56
57
 
57
- ${r.stack}`),!1}},s};var xs=new WeakMap;function zh(s){let i=xs.get(s);i&&(i.forEach(e=>clearTimeout(e)),xs.delete(s))}function Qh(s,i){return z((e,t)=>function(...r){let o=xs.get(this);o||(o=new Map,xs.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=xs.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=xs.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var Zh="trtc-sdk-v5",Kh="5.10.2-beta.14";function Xe(...s){return z((i,e)=>function(...t){try{tc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function eu(...s){return z((i,e)=>function(...t){try{tc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function tc(s,i,e,t){if(Te(s))for(let r=0;r<s.length;r++)ec.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ec.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function ec({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:F.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new B(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),K(s.type[l])&&Se(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new B({code:F.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>Er(l)?Zr(l):K(l)?l:Se(l))},value:i}})}else if(!T(s.type)&&Se(i)!==s.type)throw new B(o(5002));if(s.allowEmpty===!1){let c=J(i)&&(i===0||Number.isNaN(i)),l=K(i)&&i.trim()==="";if(c||l)throw new B(o(5003))}if(s.notLessThanZero&&J(i)&&i<0)throw new B(o(5006));if(!T(s.min)&&J(i)&&i<s.min)throw new B(o(5007));if(!T(s.max)&&J(i)&&i>s.max)throw new B(o(5008));if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new B(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new B(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new B(o(5005));let{properties:n}=s;He(n)&&bt(i)&&Object.keys(n).forEach(c=>{ec.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;He(a)&&Te(i)&&i.forEach((c,l)=>{ec.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function ge(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return z((o,n)=>function(...a){var m,f,g;function c(D,_,A){if(A&&A.includes(D))return"hided";if(e){let O=e(...a);if(a[O.argIndex]===_)return O.value}if(_===a||D in a)return _;try{return _ instanceof HTMLElement?`id: ${_.id} type:${Se(_)}`:_ instanceof MediaStreamTrack?Ln(_):(JSON.stringify(_),_)}catch(O){return`type:${Se(_)}`}}let l=this._log||C;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(D,_)=>c(D,_,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let u=t?t(...a):na[n];try{let D=o.apply(this,a),_=x();if(Qi(D)){let A=`${n.includes("Plugin")?`${((f=(m=a[0]).getName)==null?void 0:f.call(m))||""} `:" "}`;return D.then(O=>(l.info(`${n}() success ${A}${i.call(this,...a)}`),b.addSuccessEvent({key:u,cost:x()-_}),O)).catch(O=>{var Y;O=B.convertFrom.call(this,O,n,a.length===1?a[0]:a);let re=O.extraCode||O.code,Z=(Y=O.message)!=null&&Y.includes(re)?"":` code:${re}`;throw l.error(`${n}() failed ${A}${i.call(this,...a)} ${O}${Z} params: ${JSON.stringify(a,c)}`),b.addFailedEvent({key:u,error:O}),O})}return b.addSuccessEvent({key:u}),D}catch(D){D=B.convertFrom.call(this,D,n);let _=D.extraCode||D.code,A=(g=D.message)!=null&&g.includes(_)?"":` code:${_}`;throw l.error(`${n}() failed ${D}${A} params: ${JSON.stringify(a,c)}`),b.addFailedEvent({key:u,error:D}),D}})}var ic=s=>z((i,e)=>function(t,r){return p(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new B({code:F.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new B({code:F.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return tc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var rc=0,tu=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Rs(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}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 Us(s,i){if(i&&typeof i!="function")throw new B({code:F.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var mi=class mi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);rc=rc+1,this.log=i.log.createChild({id:`${this.getAlias()}${rc}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${rc}`)}getName(){return mi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return mi.startValidateRule;case"update":return mi.updateValidateRule;case"stop":return mi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new 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.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return p(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(mi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new B({code:F.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new B({code:F.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Us("onTimeUpdate",i.onTimeUpdate),Us("onEnded",i.onEnded),Us("onDurationChange",i.onDurationChange)}}),d(mi,"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){Us("onTimeUpdate",i.onTimeUpdate),Us("onEnded",i.onEnded),Us("onDurationChange",i.onDurationChange)}}),d(mi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(mi,"Name","AudioMixer");var sc=mi;var oc=0,iu,Fi=class Fi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Re("denoiser"));d(this,"workletNode");oc=oc+1,this.log=i.log.createChild({id:`${this.getAlias()}${oc}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${oc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new B({code:F.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return iu||(iu=this.doPreload(i)),iu}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Dr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Fi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Fi.startValidateRule(this.core);case"update":return Fi.updateValidateRule;case"stop":return Fi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield LT(t,w(v({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${c}`),new B({code:F.INVALID_PARAMETER,message:c});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var m;let{data:u}=l;if(u.type==="cost"){let f=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[f](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${gn(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return p(this,null,function*(){})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Fi,"updateValidateRule",{type:"object"}),d(Fi,"stopValidateRule",{type:"object"}),d(Fi,"Name","AIDenoiser");var nc=Fi;function LT(o,n){return p(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let m="Init RTCAIDenoiser failed.",f="";switch(a){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${f}`:`${m}, ${f}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var ep=Be(Qe(),1);var ru=class extends ep.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){ie.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){ie.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},PT=new ru,su=PT;function ou([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Pi(new DataView(new Uint8Array(o).buffer),!0)}function nu(s){return s.type==="empty"||s.data.byteLength===0}function au(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function cu(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 du({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-cu(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(ou),o=r.reduce((u,m)=>u+m.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let u=0;u<r.length;u++)for(let m=0;m<r[u].dataView.byteLength;m++)a.setInt8(l++,r[u].dataView.getInt8(m));for(let u=0;u<s.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return s.data=n,s}function lu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(nu(s)||!au(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Pi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var uu=0,en=class en{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);uu++,this.log=i.log.createChild({id:`${this.getAlias()}${uu}`}),this.log.info(`[sei] created id=${this.getAlias()}${uu}`),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 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:Oi?this.encode:du,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Oi?this.decode:lu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return en.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(en,"autoStart",!0),d(en,"Name","SEI");var ac=en;function mu({frame:s,onDump:i}){return i==null||i(),s}function hu({frame:s,onDump:i}){return i==null||i(),s}var tp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
58
+ ${r.stack}`),!1}},s};var wo=new WeakMap;function Sf(s){let i=wo.get(s);i&&(i.forEach(e=>clearTimeout(e)),wo.delete(s))}function ra(s,i){return be((e,t)=>function(...r){let o=wo.get(this);o||(o=new Map,wo.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=wo.get(this))==null||l.delete(n)},s);o.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=wo.get(this))==null||l.delete(n)},s);o.set(n,d)}})}var If="5.10.2-beta.16";function Ot(...s){return be((i,e)=>function(...t){try{uc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function gh(...s){return be((i,e)=>function(...t){try{uc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function uc(s,i,e,t){if(tt(s))for(let r=0;r<s.length;r++)lc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else lc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function lc({rule:s,value:i,key:e,fnName:t,className:r}){function o(d){return{code:fe.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(M(i)){if(s.required)throw new ue(o(5001));if(M(s.defaultValue)){Fe(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let d=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(d=!0),Fe(s.type[l])&&i instanceof s.type[l]&&(d=!0),Oe(s.type[l])&&lt(i)===s.type[l].toLowerCase()&&(d=!0);if(!d)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>Qs(l)?cn(l):Oe(l)?l:lt(l))},value:i}})}else if(!M(s.type)&&lt(i)!==s.type)throw new ue(o(5002));if(s.allowEmpty===!1){let d=De(i)&&(i===0||Number.isNaN(i)),l=Oe(i)&&i.trim()==="";if(d||l)throw new ue(o(5003))}if(s.notLessThanZero&&De(i)&&i<0)throw new ue(o(5006));if(!M(s.min)&&De(i)&&i<s.min)throw new ue(o(5007));if(!M(s.max)&&De(i)&&i>s.max)throw new ue(o(5008));if(Oe(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new ue(o(5004))}else if(Fe(s.instanceOf)&&!(i instanceof s.instanceOf))throw new ue(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new ue(o(5005));let{properties:n}=s;Ht(n)&&xi(i)&&Object.keys(n).forEach(d=>{lc.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=s;Ht(a)&&tt(i)&&i.forEach((d,l)=>{lc.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),Fe(s.validate)&&s.validate.call(this,i,e,t,r,this)}function Xe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return be((o,n)=>function(...a){var u;function d(m,p,g){if(g&&g.includes(m))return"hided";if(e){let f=e(...a);if(a[f.argIndex]===p)return f.value}if(p===a||m in a)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${lt(p)}`:p instanceof MediaStreamTrack?Ha(p):(JSON.stringify(p),p)}catch(f){return`type:${lt(p)}`}}let l=this._log||z;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(m,p)=>d(m,p,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let h=t?t(...a):fd[n];try{let m=o.apply(this,a),p=le();return Wr(m)?m.then(g=>(l.info(`${n}() success ${i.call(this,...a)}`),Q.addSuccessEvent({key:h,cost:le()-p}),g)).catch(g=>{var I;g=ue.convertFrom.call(this,g,n,a.length===1?a[0]:a);let f=g.extraCode||g.code,T=(I=g.message)!=null&&I.includes(f)?"":` code:${f}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${g}${T} params: ${JSON.stringify(a,d)}`),Q.addFailedEvent({key:h,error:g}),g}):(Q.addSuccessEvent({key:h}),m)}catch(m){m=ue.convertFrom.call(this,m,n);let p=m.extraCode||m.code,g=(u=m.message)!=null&&u.includes(p)?"":` code:${p}`;throw l.error(`${n}() failed ${m}${g} params: ${JSON.stringify(a,d)}`),Q.addFailedEvent({key:h,error:m}),m}})}var hc=s=>be((i,e)=>function(t,r){return A(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new ue({code:fe.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(Fe(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new ue({code:fe.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return uc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var mc=0,Eh,wr=class wr{constructor(i){this.core=i;c(this,"log");c(this,"customAudioReferenceMap",new Map);c(this,"audioRefId",0);c(this,"audioContext",dt());c(this,"localAudioWorkletNode");c(this,"screenAudioWorkletNode");c(this,"mixNode");c(this,"mixNodeConnector");c(this,"muteNode");c(this,"muteNodeConnector");mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-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){}}}preload(i){return Eh||(Eh=this.doPreload(i)),Eh}doPreload(i){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return wr.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return wr.startValidateRule(this.core);case"update":return wr.updateValidateRule;case"stop":return wr.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:d,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:h=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let u=String(Date.now()).slice(0,-3),{auth:m,sign:p,status:g,message:f}=yield mS(de(Z({},i),{timestamp:u}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${f}`),new ue({code:fe.INVALID_PARAMETER,message:f});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.localAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:u,sign:p,status:g}}),this.localAudioWorkletNode.port.onmessage=T=>{var v;let{data:I}=T;switch(I.type){case"cost":let b=(I==null?void 0:I.value)>20?"warn":(I==null?void 0:I.value)>10?"info":"debug";this.log[b](`avg cost: ${I.value} max: ${I==null?void 0:I.max}(${ns(new Date(I==null?void 0:I.maxCostTimestamp))}) hist: ${(v=I==null?void 0:I.hist)==null?void 0:v.join(" ")}`);return;case"log":this.log[I.logLevel](`${I.value}`);return;case"dump":x.emit("265",{room:e,data:I.value,type:"dump"});return}},this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.screenAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:u,sign:p,status:g}}),this.screenAudioWorkletNode.port.onmessage=T=>{var v;let{data:I}=T;switch(I.type){case"cost":let b=(I==null?void 0:I.value)>20?"warn":(I==null?void 0:I.value)>10?"info":"debug";this.log[b](`[dump-screen-audio] avg cost: ${I.value} max: ${I==null?void 0:I.max}(${ns(new Date(I==null?void 0:I.maxCostTimestamp))}) hist: ${(v=I==null?void 0:I.hist)==null?void 0:v.join(" ")}`);return;case"log":this.log[I.logLevel](`[dump-screen-audio] ${I.value}`);return;case"dump":x.emit("265",{room:e,data:I.value,type:"dump-screen-audio"});return}}}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.muteNode||(this.muteNode=this.audioContext.createConstantSource(),this.muteNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.muteNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.muteNode,this.screenAudioWorkletNode),M(n)||n.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),x.emit("266",{room:this.core.room,type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})}),M(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),M(d)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:d}})})}update(i){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;M(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),x.emit("266",{room:this.core.room,type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),x.emit("266",{room:this.core.room,type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),M(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),M(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.muteNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.muteNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}};c(wr,"updateValidateRule",{type:"object"}),c(wr,"stopValidateRule",{type:"object"}),c(wr,"Name","AudioProcessor");var pc=wr;function hS(s,i=S.MAIN){return`https://${tr[i]||dc(s,i)}/api/v1/audioAiAuth`}function mS(r){return A(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${hS(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let m=ms(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAudioProcessor failed.",g="";switch(d){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:l?`${p} Reason: ${l}. ${g}`:`${p}, ${g}`}})}var fc=0,Th=class{constructor(i,e){c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new Io(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&&(M(i.volume)||(this.volume=i.volume),M(i.loop)||(this.loop=i.loop),M(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 Mo(s,i){if(i&&typeof i!="function")throw new ue({code:fe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ir=class ir{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}getName(){return ir.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ir.startValidateRule;case"update":return ir.updateValidateRule;case"stop":return ir.stopValidateRule}}start(i){return A(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 Th(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&x.emit("266",{room:this.core.room,type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),Q.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return A(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),M(t)||n.setOperation(t),M(r)||n.seek(r),this.kvUpload(i)})}stop(e){return A(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&x.emit("266",{room:this.core.room,type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:h}=i;e&&Q.addCount({key:502711}),t&&Q.addCount({key:502703}),r&&Q.addCount({key:502704}),o&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),a&&Q.addCount({key:502707}),typeof d!="function"&&Q.addCount({key:502709}),typeof h!="function"&&Q.addCount({key:502710}),typeof l!="function"&&Q.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&x.emit("266",{room:this.core.room,type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};c(ir,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new ue({code:fe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new ue({code:fe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Mo("onTimeUpdate",i.onTimeUpdate),Mo("onEnded",i.onEnded),Mo("onDurationChange",i.onDurationChange)}}),c(ir,"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){Mo("onTimeUpdate",i.onTimeUpdate),Mo("onEnded",i.onEnded),Mo("onDurationChange",i.onDurationChange)}}),c(ir,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(ir,"Name","AudioMixer");var _c=ir;var gc=0,Sh,Mr=class Mr{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",dt("denoiser"));c(this,"workletNode");gc=gc+1,this.log=i.log.createChild({id:`${this.getAlias()}${gc}`}),this.log.info(`created id=${this.getAlias()}${gc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new ue({code:fe.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Sh||(Sh=this.doPreload(i)),Sh}doPreload(i){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:d}=yield fS(t,de(Z({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${d}`),new ue({code:fe.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var u;let{data:h}=l;if(h.type==="cost"){let m=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[m](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${ns(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(u=h==null?void 0:h.hist)==null?void 0:u.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return A(this,null,function*(){})}stop(){return A(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};c(Mr,"updateValidateRule",{type:"object"}),c(Mr,"stopValidateRule",{type:"object"}),c(Mr,"Name","AIDenoiser");var Ec=Mr;function fS(o,n){return A(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:h}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:d};let u="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:m="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:m="Your version is not supported.";break}return{auth:!1,status:h,message:d?`${u} Reason: ${d}. ${m}`:`${u}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Af=gt(Mt(),1);var Ih=class extends Af.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return A(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ze&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Me.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)&&z.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){Me.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},_S=new Ih,Ah=_S;function Ch([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 vr(new DataView(new Uint8Array(o).buffer),!0)}function Rh(s){return s.type==="empty"||s.data.byteLength===0}function yh(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function bh(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 vh({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-bh(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Ch),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),d=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,d.getInt8(h));return s.data=n,s}function Nh({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Rh(s)||!yh(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new vr(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Dh=0,sa=class sa{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);Dh++,this.log=i.log.createChild({id:`${this.getAlias()}${Dh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Dh}`),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 vh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Nh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(ne.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:Ar?this.encode:vh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ar?this.decode:Nh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return sa.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(sa,"autoStart",!0),c(sa,"Name","SEI");var Tc=sa;function kh({frame:s,onDump:i}){return i==null||i(),s}function Oh({frame:s,onDump:i}){return i==null||i(),s}var Cf=()=>{let s=window.navigator&&window.navigator.userAgent||"",i=/iPad/i.test(s)||/iPhone/i.test(s),e=/Android/i.test(s);return i||e},Re={LOG_BUTTON:"Log",NETWORK_BUTTON:"Network",DUMP_BUTTON:"Dump",DUMPING_BUTTON:"Dumping",END_BUTTON:"End",UPLOAD_BUTTON:"Upload Log",EXPORT_BUTTON:"Export Log",HIDE_BUTTON:"Hide",GO_BOTTOM:"goBottom",BACK_TOP:"backTop",CLEAR_LOG:"Clear Log",UPLINK:"Uplink",DOWNLINK:"Downlink",NO_DATA:"No Data",BASIC:"Basic",DURATION:"Duration",VIDEO:"Video",AUDIO:"Audio",SCREEN:"Screen"},Rf=s=>s.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d").replace(">","&gt;").replace(">","&lt;"),ss={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
58
59
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
59
60
  2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
60
61
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
61
- 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(s=>{tp[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var PM=Object.keys(tp);var wT=0,cc,tn=class tn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++wT}`}),this.log.info("created")}getName(){return tn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return p(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return p(this,null,function*(){var i;try{if(cc)yield cc;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Zh}@${ke}/assets/debug-dialog.js`;cc=this._core.fileDownloader.loadScript(e),yield cc}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):mu,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):hu,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return mu({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return hu({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(tn,"Name","Debug"),d(tn,"autoStart",!0);var dc=tn;var ip=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},lc=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=me(e,$.INIT),this.stopOB=et(),this.startOB=et(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=et(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),le(l,xe(this.stopOB),ye(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:ip(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),le(l,Ui(1),$l(qo))};le(this.startOB,Jo(0),Ns(a),xe(this.stopOB),ye(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:ip(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return xi()(e=>p(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},xT={type:"object"},rn=class rn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return rn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return rn.Name}getValidateRule(i){return xT}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new lc(this.core,t,i);return le(r.trackDoneOB,Ui(1),ye(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new lc(this.core,i.track,i))}}};d(rn,"Name","TRTCAudioDecoder");var sn=rn;var uc=class{constructor(){d(this,"log");this.log=C.createLogger({id:"exp"})}call(i,e){return p(this,null,function*(){return ne(this[i])?this[i](e):Promise.reject(new y({code:S.INVALID_PARAMETER,message:P({key:L.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return p(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:o,channelCount:n}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let f=c.getPCM(g=>{e.emit(M.AUDIO_FRAME,g)},m.userId);l.set(m.userId,f)}});else{if(l.get(r))return;let m=c.getPCM(f=>{e.emit(M.AUDIO_FRAME,f)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:f}=m,g=l.get(f);g==null||g.abort("disable"),l.delete(f)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}};N([Oh({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],uc.prototype,"enableAudioFrameEvent",1);var rp=new uc;var sp=0,on=new Set,Ve=null;Mc(Kh);_s.checkStorage();Hd();var UT={RtcError:B,ErrorCode:F,ErrorCodeDictionary:Ut},q=class q extends op.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",C.createLogger({id:`t${++sp}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");this._room=new e(v({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(sc,t.assetsPath),this._use(nc,t.assetsPath),this._use(sn,t.assetsPath||Tn),this._use(dc),t.enableSEI&&ko&&this._use(ac),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(M.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new B({code:F.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Xh(this,"trtc")}static create(e){}static _create(e,t){Lh();let r=new q(e,t||{});return on.add(r),r}get room(){return this._room}_listenEvents(){Ge(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}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(M.ERROR,B.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(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,to),downlinkRTT:Math.min(e.downlinkRTT,to)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ge(r,r).add("player-state-changed",o=>{let n=w(v({},o),{userId:e.userId});r.kind===h.VIDEO&&(n.streamType=or(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,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{ve(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,w(v({},e),{streamType:or(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new B({code:F.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,l,u,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((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,to),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/Tt},video:e.msg_up_stream_info.msg_video_status.filter(f=>t[f.uint32_video_stream_type]).map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_enc_fps,videoType:t[f.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(f=>({userId:f.msg_user_info.str_identifier,audio:{bitrate:(f.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(f.msg_audio_status.uint32_audio_level||0)/Tt,point2pointDelay:(f.msg_audio_status.uint32_audio_p2p_delay||0)+(f.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:f.msg_audio_status.uint32_audio_cache_ms||0},video:f.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type],point2pointDelay:(g.uint32_video_p2p_delay||0)+(g.uint32_video_cache_ms||0),jitterBufferDelay:g.uint32_video_cache_ms||0}))}))};this.emit(M.STATISTICS,r)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(M.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(M.FIRST_VIDEO_FRAME,w(v({},e),{streamType:or(e.streamType)}))}).add("audio-frame",e=>{this.emit(M.AUDIO_FRAME,e)}),Ge(this,Me).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=>p(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ve&&Ve.deviceId===eo){let t=(yield rr()).find(r=>r.deviceId===eo);t&&Ve.groupId!==t.groupId&&(Ve=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield rr())[0];if(!t||!Ve||Ve.groupId===t.groupId)return;let r=Ve.deviceId===e.deviceId,o=Ve.deviceId===eo&&Ve.deviceId===t.deviceId;(r||o)&&(Ve=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||Tn)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(qh.call(this,{TRTC:q,room:this._room,errorModule:UT,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return p(this,null,function*(){var c,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!K(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,he(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),su.start()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){ve(this),this.removeAllListeners(),this._room.destroy(),on.delete(this),on.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)}),this._plugins.clear(),E.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new Et(this._room.audioManager),a={},c={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&J(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(K(o.profile)?In[o.profile]&&n.setProfile(In[o.profile]):n.setProfile(o.profile)),J(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(M.ERROR,new B({code:F.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=B.convertFrom(l.error)),this.emit(M.PUBLISH_STATE_CHANGED,w(v({},l),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),Ge(n,n).add("player-state-changed",l=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,w(v({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),E.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Wt(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),E.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ve(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new Je(this._room.videoManager),c={},l={};he(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?c.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(n.retryWhenExactFailed)||(c.retryWhenExactFailed=n.retryWhenExactFailed),n.qosPreference&&(c.contentHint=Yo(n.qosPreference)),T(n.profile)||(K(n.profile)?Rt[n.profile]&&a.setProfile(Rt[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.small)||(T(n.smallMode)||(this._room.smallMode=n.smallMode),he(n.small)&&n.small===!1?a.stopSmall():a.updateSmallConfig(Ps(n.small,!0)))),a.once("first-video-frame",u=>{this.emit(M.FIRST_VIDEO_FRAME,w(v({},u),{streamType:or(u.streamType)}))}),a.on("5",u=>{this.emit(M.ERROR,new B({code:F.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let m;u.error&&(m=B.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,w(v({},u),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),T(o)||(yield a.setMute(o)),Ge(a,a).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,w(v({},u),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=w(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};n&&(T(n.profile)||(K(n.profile)?Rt[n.profile]&&this._localVideoTrack.setProfile(Rt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Yo(n.qosPreference)),T(n.small)||(he(n.small)&&!n.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Ps(n.small,!0)))),this._room.isJoined&&!T(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Wt(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ve(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new at(this._room.videoManager);n.on("4",m=>{let f;m.error&&(f=B.convertFrom(m.error)),this.emit(M.PUBLISH_STATE_CHANGED,w(v({},m),{error:f}))}),n.once("first-video-frame",m=>{this.emit(M.FIRST_VIDEO_FRAME,w(v({},m),{streamType:or(m.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},l={};o&&(T(o.profile)||(K(o.profile)?An[o.profile]&&n.setProfile(An[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(c.contentHint=Yo(o.qosPreference)));let u=yield n.capture(c);if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new ci(this._room.audioManager),yield a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Ge(n,n).add("player-state-changed",m=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,w(v({},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=w(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=Yo(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!T(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Wt(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var A,O;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror));let u=null,m=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(m!=null&&m.muteState.hasVideo)&&(u=m.remoteVideoTrack),o==="sub"&&(m!=null&&m.muteState.hasAuxiliary)&&(u=m.remoteAuxiliaryTrack),!u)return;let{config:f}=c;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:u,prevConfig:f}),Wt(f,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(A=f.option)==null?void 0:A.receiveWhenViewVisible:n.receiveWhenViewVisible,D=T(t)?f.view:t,_=T(n==null?void 0:n.viewRoot)?(O=f.option)==null?void 0:O.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:D,receiveWhenViewVisible:g,viewRoot:_})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return p(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(M.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:o}=this.room.audioManager;o.get("")||o.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{Hh.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:o}=this.room.audioManager;o.forEach(n=>{n==null||n.abort("off")}),o.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(K(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return p(this,null,function*(){(yield rr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Ve=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),c=J(a)?a:100;o.volume=c,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),le(me(n,"decode-failed"),xe(me(n,$.INIT)),ye(()=>{this.startPlugin(sn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),E.emit("115",{userId:t,room:this.room})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),E.emit("116",{userId:e.userId,room:this.room})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;le(me(e,"decode-failed"),xe(me(e,$.INIT)),Wl(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Ur(me(e,"decode-downgrade-state-changed")),ye(n=>{o=n.state,this.emit(M.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,w(v({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),T(e)&&o&&o.view&&!Kr(t)){let a=ts(o.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=ts(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(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:or(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${or(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Te(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(f=>{f.forEach(g=>{l.set(g.target,g.isIntersecting),e.log.info(`view ${g.target.id} is${g.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(D=>D)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(ts(t));l.forEach((f,g)=>{m.has(g)||(a.unobserve(g),l.delete(g))}),m.forEach(f=>{l.set(f,!0),a.observe(f)}),a.takeRecords().forEach(f=>{l.set(f.target,f.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),zh(this),this._room.remotePublishedUserMap.forEach(e=>{ve(e.remoteAudioTrack),ve(e.remoteVideoTrack),ve(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ve(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ve||ys(Ve))&&(this._initActiveSpeaker(),E.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return p(this,null,function*(){if(Ve&&!ys(Ve))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ve});else{let e=yield rr();e[0]&&!ys(e[0])?(Ve=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):E.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:w(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),b.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),b.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return p(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),rp.call(e,v({trtcInstance:this},t))})}static setLogLevel(e,t){C.setLogLevel(e),T(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return la()}static getCameraList(e=!0){return _t(e)}static getMicrophoneList(e=!0){return ot(e)}static getSpeakerList(e=!0){return rr(e)}static setCurrentSpeaker(e){return p(this,null,function*(){if(pe&&(e===It.SPEAKER||e===It.HEADSET)){let r=yield q.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;on.forEach(n=>p(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield rr()).forEach(r=>{r.deviceId===e&&(on.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Ve=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a,max:c}){switch(a&&(br.version=a),e){case"count":br.addCount({key:t,useUV:n});break;case"enum":br.addEnum({key:t,value:r,useUV:n});break;case"number":br.addNumber({key:t,value:r,split:o,max:c});break}}};d(q,"_loggerManager",C),d(q,"EVENT",M),d(q,"ERROR_CODE",F),d(q,"TYPE",It),d(q,"frameWorkType",30),N([ge({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],q.prototype,"use",1),N([Xe(Ue.TRTC.enterRoom),ar("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),z(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),ge()],q.prototype,"enterRoom",1),N([ge()],q.prototype,"exitRoom",1),N([Xe(Ue.TRTC.switchRole),$r("room",{merge:(e,t)=>t}),ge()],q.prototype,"switchRole",1),N([ge()],q.prototype,"destroy",1),N([Xe(Ue.TRTC.startLocalAudio),ar("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),ge()],q.prototype,"startLocalAudio",1),N([Xe(Ue.TRTC.updateLocalAudio),$r("audio",{debounce:{delay:200,getKey:()=>`${sp}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),ge()],q.prototype,"updateLocalAudio",1),N([cr("audio"),ge()],q.prototype,"stopLocalAudio",1),N([Xe(Ue.TRTC.startLocalVideo),ar("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),ge()],q.prototype,"startLocalVideo",1),N([Xe(Ue.TRTC.updateLocalVideo),$r("video"),ge()],q.prototype,"updateLocalVideo",1),N([cr("video"),ge()],q.prototype,"stopLocalVideo",1),N([Xe(Ue.TRTC.startScreenShare),ar("screen",()=>!0),ge()],q.prototype,"startScreenShare",1),N([Xe(Ue.TRTC.updateScreenShare),$r("screen"),ge()],q.prototype,"updateScreenShare",1),N([ge()],q.prototype,"stopScreenShare",1),N([Xe(Ue.TRTC.startRemoteVideo),ar(e=>`v${e.userId}${e.streamType}`,()=>!0),ge({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),N([Xe(Ue.TRTC.updateRemoteVideo),$r(e=>`v${e.userId}${e.streamType}`),ge({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),N([Xe(Ue.TRTC.stopRemoteVideo),z(e=>function(t){return p(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),ge({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),N([cr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),N([Xe(...Ue.TRTC.muteRemoteAudio),ge({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),N([eu(...Ue.TRTC.setRemoteAudioVolume),Qh(200,e=>e),ge({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),N([ic("start"),Ke(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),ar((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ge({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Md[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],q.prototype,"startPlugin",1),N([ic("update"),$r((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ge({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ld[e.getName()]})],q.prototype,"updatePlugin",1),N([ic("stop"),cr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),ge({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Pd[e.getName()]})],q.prototype,"stopPlugin",1),N([eu(...Ue.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),N([ge()],q.prototype,"getVideoSnapshot",1),N([ge()],q.prototype,"_setCurrentSpeaker",1),N([ar(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),N([z(e=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(w(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),cr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),N([cr("room")],q.prototype,"_exitRoom",1),N([cr("screen")],q.prototype,"_stopScreenShare",1),N([Xe(...Ue.TRTC.sendSEIMessage),ql({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),N([Xe(Ue.TRTC.sendCustomMessage),ql({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),N([Xe(Ue.TRTC.create)],q,"_create",1);var pu=q,nn=pu;var fu=class{constructor(){d(this,"_set",new Set);E.on(I.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function VT(){return p(this,null,function*(){let s,i;try{let m=yield ot();s=m&&m.length}catch(m){}try{let m=yield _t();i=m&&m.length}catch(m){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=ti.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ie.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),ie.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function np(){return z(s=>{let i=new fu;return function(e,t,r){return p(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new y({code:S.INVALID_OPERATION,message:P({key:L.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new y({code:S.INVALID_OPERATION,message:P({key:L.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),E.emit(I.JOIN_START,{room:this,roomId:o,params:e});let n=ct.getEnv();n||(n=_i.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Cn.OLD_CLOUD_LADDER)?n=_i.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Cn.WEBRTC)&&(n=_i.WEBRTC))),ie.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),ti.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,VT.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!ct.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=ct.performanceNow(),E.emit(I.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&ie.uploadEvent({log:`stat-conv-${Number(Lt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),E.emit(I.JOIN_FAILED,{room:this,error:a}),a}})}})}var ap=()=>z(s=>function(...i){return p(this,null,function*(){E.emit(I.LEAVE_START,{room:this}),yield s.call(this,...i),E.emit(I.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function cp(){return z(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var lp=Be(Qe());var be={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Bt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},dp=[Bt.UPDATE_REMOTE_MUTE_STAT,Bt.UPLINK_NETWORK_STATS,Bt.USER_LIST_RES,Bt.MUTE_RESULT,Bt.SERVER_FIRST_PACKAGE_RECEIVED,Bt.RECEIVE_CUSTOM_MSG],H={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"},Q={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var mc=new Set;function up(s){let i=[...mc.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Vs=class extends lp.default{constructor(e){var r,o,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-mc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,mc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=C.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=x();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Sr(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 y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===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){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(be.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(be.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=so(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Bt),c=Object.keys(Bt)[n.indexOf(r)],l=H[c]||r;switch(dp.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Bt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Wu(o.svrTime),this._log.info(`ChannelSetup Success ${x()-this._connectStartTime}`),b.addSuccessEvent({key:521701,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.emit(be.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:P({key:L.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),b.addFailedEvent({key:521701,error:u}),this.emit(be.SETUP_FAILED,u)}break}case Bt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{if(!this.room.joinParams)return;Vt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?h.MAIN:h.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:H.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),b.addSuccessEvent({key:521702,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(b.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let 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+=so(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let m=setTimeout(()=>{this.off(o,g);let _=new y({code:S.API_CALL_TIMEOUT,message:P({key:L.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(_),u(_)},r),f=Date.now(),g=_=>{_.data.seq===D&&(clearTimeout(m),this.off(o,g),c&&(_.data.receiveTime=Date.now()),l(_))};this.on(o,g);let D=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return jt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(be.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),mc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(H.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(H.JOIN_ROOM_RESULT,t))};this.on(H.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(be.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(be.CONNECTED):e==="DISCONNECTED"&&this.emit(be.DISCONNECTED))}};N([ht({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Vs.prototype,"connect",1);var mp=Be(Qe());var _u=0,gu=!1,hc=new Set,FT=s=>_u>2&&!gu&&hc.size===0&&s,Tu=!1,it=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new mp.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=C.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,b.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&b.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,b.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&b.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(),hc.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new y({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return yt;let i=null;if(this._isUplink){if(!ir()||this._peerConnection.getSenders().length===0)return yt;i=this._peerConnection.getSenders()[0].transport}else{if(!vr()||this._peerConnection.getReceivers().length===0)return yt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:yt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===fe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===fe.FAILED||i.target.connectionState===fe.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new y({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===fe.CONNECTED||i.target.connectionState===fe.COMPLETED)&&(this.logSelectedCandidate(),ie.logSuccessEvent({userId:this._room.userId,eventType:rt.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(_u=0,gu=!1,Tu=!0,hc.add(this)):hc.delete(this),E.emit(I.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(tr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{E.off(I.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});_u+=1,FT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),gu=!0,this._emitter.emit("firewall-restriction")),e(a)},Ks);E.on(I.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(be.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=gi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new y({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:P({key:this._isUplink?L.UPLINK_RECONNECTION_FAILED:L.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(be.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([nt(521712,!1)],it.prototype,"setOffer",1),N([nt(521713,!1)],it.prototype,"setAnswer",1);var Au=Be(Iu());var Ce=function(s){return Au.default.parse(s)},At=function(s){return Au.default.write(s)},Sp=function(s){let i=Ce(s);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),At(i)};function Ip(s){let i=Ce(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 l=c.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),At(i)}function pc(s){return Object.keys(s).filter(i=>s[i])}var Fs=class Fs extends it{constructor(e){super(w(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new wi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ui(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Ms(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Si(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===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===Zs?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
62
- `),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
63
- `)}addSPSDescription(e){let t=Ce(e);return t.media.forEach(r=>{r.type===h.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),At(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=Ce(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),At(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===fe.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===fe.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${pc(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=Q.UNSUBSCRIBE,n=H.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Q.SUBSCRIBE_CHANGE,n=H.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:P({key:L.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Q.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:H.SUBSCRIBE_RESULT,timeout:Gc});if(!this._peerConnection){let a=new y({code:S.INVALID_OPERATION,message:P({key:L.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};mt()&&this._sdpSemantics===zi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:ee.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:ee.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:ee.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield da();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=Ip(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Sp(t.sdp),this._sdpSemantics===zi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===hr)throw new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new y({code:t,message:P({key:L.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ce(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(Zs)});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(Zs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Vc)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return p(this,null,function*(){if(!(Fe(Fs.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=Nt(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}};N([z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Fs.prototype,"subscribe",1),N([nt(521717,!1)],Fs.prototype,"unsubscribe",1),N([Ke(it.prototype.afterConnect),ya(it.prototype.beforeConnect)],Fs.prototype,"connect",1);var Cu=Fs,Ru=Cu;var Cp={voiceActivityDetection:!1},$s=class $s extends it{constructor(e){super(w(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Kt()?(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 p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),mt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||h.AUDIO,{direction:ee.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:ee.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||h.VIDEO,{direction:ee.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:ee.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(l&&(u[0].sender.track||m.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let f=o?3:1;yield u[f].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),m.push(f),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(ee.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 p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ee.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ee.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Kt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ee.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Q.PUBLISH_STATE_CHANGE,data:t,responseCommand:H.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Q.UNPUBLISH,commandDesc:"unpublish",responseCommand:H.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),ei){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:H.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),mt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===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&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ee.INACTIVE&&(yield this.setTransceiverDirection(ee.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Kt()&&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 Je&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===zr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Ce(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;Kt()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ne(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),mt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===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(ee.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!ae)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
64
- `).map(l=>{if(l.match(new RegExp(`a=(${ee.INACTIVE}|${ee.RECVONLY}|${ee.SENDONLY})`))&&a++,t.includes(a)){if(e===ee.INACTIVE&&l.includes(`a=${ee.RECVONLY}`))return o=!0,`a=${e}`;if(e===ee.SENDONLY&&l.includes(`a=${ee.INACTIVE}`))return o=!0,`a=${ee.RECVONLY}`}return l}).join(`\r
65
- `);o&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:c}))})}removeTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===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 p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(mt()?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 p(this,null,function*(){try{let r=yield this._peerConnection.createOffer(Cp);ae&&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:Q.PUBLISH_CHANGE,data:n,responseCommand:H.UPDATE_OFFER_RESULT,timeout:Hc,commandDesc:"update offer"}),{code:c,message:l}=a.data;c!==0&&this.checkPublishResultCode(c,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:o}){if(!Oo())return o?t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e):void 0;let a,c=this._peerConnection.getSenders();if(mt()){let l=0;t===h.VIDEO&&(r===h.SMALL?l=2:r===h.AUXILIARY?l=3:l=1),a=c[l]}else a=c.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),o}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),o)return t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,r){let o="AS";ae&&(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
66
- `:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return ae&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
62
+ 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(s=>{ss[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var yf=Object.keys(ss);var Mf=gt(vf());var je="trtc_debug_dialog",os=`${je}_activated`,Sc=`${je}_switch`,xh=`${je}_mask`,Ic=`${je}_panel`,Lh=`${je}_tabber`,xo=`${je}_tab`,Ph=`${je}_topbar`,Vs=`${je}_toptab`,Lr=`${je}_content`,Nc=`${je}_has_topbar`,Bh=`${Lr}_log`,Bs=`${Lr}_network`,Ur=`${je}_dump`,oa=`${Bs}_title`,ca=`${Bs}_basic`,Ac=`${Bs}_local`,Cc=`${Bs}_remote`,Mh=`${Ur}_title`,Lo=`${Ur}_local`,rr=`${Ur}_remote`,Nf=`${rr}_hook`,Dc=`${je}_banner`,xf=`${Dc}_item`,Df=`${je}_toolbar`,na=`${je}_tool`,Pr=`${je}_item`,Lf=`${Pr}_debug`,Pf=`${Pr}_info`,Uf=`${Pr}_warn`,Vf=`${Pr}_error`,kf=`${je}_back_top`,Of=`${je}_go_bottom`,Rc=`${Ur}_local_audio`,yc=`${Ur}_local_video_main`,bc=`${Ur}_local_video_aux`,aa=`${je}_tooltip`,Bf=`${ca}_network_info`,$f=`${ca}_room_info`,vc=`${Bh}_controller`,xr="success",wf="warning",Po="failed",Uh=0,Vh=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.addStyle(),this.addDialog()}addDialog(){var e;let i=document.createElement("template");i.innerHTML=`<div id="${je}" class="${je}"><div class="${Sc}">Debug#${++Uh}</div><div class="${xh}"></div><div class="${Ic}"><div class="${Lh}"><a class="${xo} ${os}" data-tab="log">${Re.LOG_BUTTON}</a><a class="${xo}" data-tab="network">${Re.NETWORK_BUTTON}</a><a class="${xo}" data-tab="dump">${Re.DUMP_BUTTON}</a></div><div class="${vc}"><div data-type="back_top">${Re.BACK_TOP}</div><div data-type="go_bottom">${Re.GO_BOTTOM}</div><div data-type="clear_log">${Re.CLEAR_LOG}</div></div><div class="${Ph}"><a class="${Vs} ${os}" data-type="all">All</a><a class="${Vs}" data-type="debug">Debug</a><a class="${Vs}" data-type="info">Info</a><a class="${Vs}" data-type="warn">Warn</a><a class="${Vs}" data-type="error">Error</a></div><div class="${Lr} ${Nc}"><div class="${Bh}"></div><div class="${Bs}"><div class="${oa}">${Re.BASIC}</div><div class="${ca}"><div class="${$f}"></div><div class="${Bf}">${Re.NO_DATA}</div></div><div class="${oa}">${Re.UPLINK}</div><div class="${Ac}">${Re.NO_DATA}</div><div class="${oa}">${Re.DOWNLINK}</div><div class="${Cc}">${Re.NO_DATA}</div></div><div class="${Ur}"><div class="${Mh}">${Re.UPLINK}</div><div class="${Lo}"><div id="${Rc}"><span>${Re.AUDIO} - ${Re.DURATION}(s):</span><input type="number" min=0 value=0></input><button class="dump">${Re.DUMP_BUTTON}</button><button class="end-dump" disabled>${Re.END_BUTTON}</button></div><div id="${yc}"><span>${Re.VIDEO} - ${Re.DURATION}(s):</span><input type="number" min=0 value=10></input><button class="dump">${Re.DUMP_BUTTON}</button><button class="end-dump" disabled>${Re.END_BUTTON}</button></div><div id="${bc}"><span>${Re.SCREEN} - ${Re.DURATION}(s):</span><input type="number" min=0 value=10></input><button class="dump">${Re.DUMP_BUTTON}</button><button class="end-dump" disabled>${Re.END_BUTTON}</button></div></div><div class="${Mh}">${Re.DOWNLINK}</div><div class="${rr}"><div class="${Nf}">userId:<input id="dump-remote-video-hook-userid" value='*' />duration:<input id="dump-remote-video-hook-duration" min='1' value='10' type='number' />mediaType:<select id="dump-remote-video-hook-mediaType" value='main' ><option value='main' checked>Video</option><option value='sub'>Screen</option></select><button id="dump-remote-video-hook-button">dump if video is available</button></div></div></div></div><div class="${Dc}"></div><div class="${Df}"><a id="trtc_upload" class="${na}">${Re.UPLOAD_BUTTON}</a><a id="trtc_export" class="${na}">${Re.EXPORT_BUTTON}</a><a id="trtc_hide" class="${na}">${Re.HIDE_BUTTON}</a></div></div></div>`,(e=this.shadowRoot)==null||e.appendChild(i.content.firstChild)}addStyle(){var e;let i=document.createElement("style");i.textContent=`#${je}{font-size:14px;--DD-BG-0:#ededed;--DD-BG-1:#f7f7f7;--DD-BG-2:#fff;--DD-BORDER:rgba(0,0,0,0.1);--DD-ERROR:red;--DD-WARN:#fa9d3b;--DD-INFO:#000;--DD-DEBUG:#10aeff;--DD-WARN-BG:#fff3cc;--DD-ERROR-BG:#ffe6e6;}#${je} a,.${Sc}{cursor:pointer;}.${je}{color:black;}.${Sc}{display:block;position:fixed;right:50px;bottom:${150+Uh*50}px;border-radius:5px;background-color:#07c160;color:#fff;padding:5px 10px;z-index:10000;}.${xh}{display:none;position:fixed;left:0;top:0;right:0;bottom:0;z-index:10001;background-color:rgb(0,0,0,0.6);}.${Ic}{background-color:#ededed;display:none;position:fixed;min-height:85%;left:60%;right:0;bottom:0;z-index:10002;border:1px solid var(--DD-BG-0);}@media (max-width:768px) {.${Ic}{left:0;}}.${Lh}{display:flex;height:2em;border-bottom:1px solid var(--DD-BORDER);}.${xo}{padding:0 20px;border-right:1px solid rgba(0,0,0,0.1);line-height:2em;color:black;}.${xo}.${os}{background-color:var(--DD-BG-2);}.${xo}.disabled{cursor:not-allowed;background-color:#ededed;color:#999;}.${Ph}{height:2em;display:flex;flex-direction:row;}.${Vs}{width:20%;text-align:center;line-height:2em;border-right:1px solid var(--DD-BORDER);border-bottom:1px solid var(--DD-BORDER);color:black;}.${Vs}.${os}{border-bottom:1px solid #1485ee;background-color:var(--DD-BG-2);}.${Lr}{background-color:#fff;position:absolute;left:0;right:0;top:2em;bottom:8em;overflow-y:scroll;overflow-x:hidden;}.${Lr}.${Nc}{top:4em;bottom:10em}.${Bs}{display:none;}.${Ur}{display:none;}.${oa},.${Mh}{line-height:2em;text-align:center;background-color:var(--DD-BG-0);border-bottom:1px solid var(--DD-BORDER);}.${ca},.${Ac},.${Cc}{text-align:center;border-bottom:1px solid var(--DD-BORDER);}.${Lo},.${rr}{display:flex;flex-direction:column;padding:0.5em 0;justify-content:center;align-items:center;}.${Lo} div input{margin:0 10px;height:1.5em;width:4em;}.${Lo} div {padding:10px 0;border-radius:5px;}.${Lo} div button,.${rr} div button {cursor:pointer;height:1.8em;border-radius:5px;margin-right:5px;}.${Lo} div button[disabled],.${rr} div button[disabled]{cursor:not-allowed;}.${rr} select {height:1.8em;margin:0 10px;}.${rr} div input{margin:0 10px;height:1.5em;width:4em;}.${Nf} {line-height:3em;padding:0.5em;}.${oa}{text-align:center;background-color:var(--DD-BG-0);border-bottom:1px solid var(--DD-BORDER);}.${ca},.${Ac},.${Cc}{text-align:center;border-bottom:1px solid var(--DD-BORDER);}.${Pr}{border-bottom:1px solid var(--DD-BG-0);padding:5px 10px;overflow-wrap: break-word;}.${Vf}{color:var(--DD-ERROR);background-color:var(--DD-ERROR-BG);}.${Uf}{color:var(--DD-WARN);background-color:var(--DD-WARN-BG);}div .${Pf}{color:var(--DD-INFO);}.${Lf}{color:var(--DD-DEBUG);}.${Dc}{position:absolute;left:0;right:0;bottom:2em;height:6em;border-bottom:1px solid var(--DD-BORDER);display:flex;flex-direction:column;overflow-y:scroll;background-color:var(--DD-BG-1);}.${xf}{border-bottom:1px solid var(--DD-BORDER);padding:5px 10px;overflow-wrap: break-word;}.${Df}{position:absolute;line-height:2em;display:flex;flex-direction:row;left:0;right:0;bottom:0;}.${na}{flex:1;color:black;text-align:center;background-color:#ededed;border-right:1px solid var(--DD-BORDER);}#${je} .${kf},#${je} .${Of}{position:absolute;height:2em;width:6em;right:2em;border-radius:5px;background-color:rgba(30,136,229,0.8);z-index:10003;cursor:pointer;padding:0 5px;line-height:2em;color:white;text-align:center;}.${Of}{bottom:9em;}.${kf}{bottom:11.5em;}#${je} .${na}.disable{cursor:not-allowed;background-color:#ededed;color:#999;}.${aa} {position:relative;display:inline-block;}.${aa} .tooltiptext{visibility:hidden;width:180px;background-color:black;color:#fff;text-align:center;padding:5px 0;border-radius:6px;position:absolute;}.${aa} .tooltip-top {bottom:125%;left:50%;margin-left:-90px;}.${aa}:hover .tooltiptext{visibility:visible;}.${vc}{position:absolute;left:0;right:0;bottom:8em;height:2em;display:flex;align-items:center;}.${vc} div{flex:1;cursor:pointer;border-right:1px solid var(--DD-BORDER);text-align: center;}`,(e=this.shadowRoot)==null||e.appendChild(i)}};customElements.define("trtc-basic-debug-dialog",Vh);var da=class{constructor(i,e,t,r){c(this,"_dialogNode",null);c(this,"_switchNode",null);c(this,"_maskNode",null);c(this,"_panelNode",null);c(this,"_logContentNode",null);c(this,"_networkContentNode",null);c(this,"_dumpContentNode",null);c(this,"_tabNodes",[]);c(this,"_toptabNodes",[]);c(this,"_hasMove",!1);c(this,"_showDialog",!1);c(this,"_isMobile",!1);c(this,"_showLogType","all");c(this,"prevBytesSent",0);c(this,"prevBytesReceived",0);c(this,"_core");c(this,"_log");c(this,"_logList",[]);c(this,"isUploading",!1);c(this,"publishMap",new Map);c(this,"dumpLocalVideoMap");c(this,"dumpRemoteVideoMap");c(this,"eventMap",new Map);c(this,"switchPos",{x:0,y:0,startX:0,startY:0,endX:0,endY:0,isTouchEnd:!1});c(this,"handleLeaveSuccess",({room:i})=>{var t,r;if(!this.hitTest(i))return;let e=(r=(t=this._dialogNode)==null?void 0:t.shadowRoot)==null?void 0:r.querySelector(`.${rr}`);for(let o of this.publishMap.values())e==null||e.removeChild(o);this.publishMap.clear()});c(this,"handleJoinSuccess",({room:i})=>{var t,r;if(!this.hitTest(i))return;let e=(r=(t=this._dialogNode)==null?void 0:t.shadowRoot)==null?void 0:r.querySelector(`.${$f}`);e.innerHTML=`sdkAppId: ${i.sdkAppId}<br/>roomId: ${i.roomId}<br/>userId: ${i.userId}<br/>`});c(this,"handleRemoteVideoAvailable",i=>{let e=i.streamType==="sub"?"auxiliary":"main";this.renderDumpTab(i.userId,"remote",e,"publish")});c(this,"handleRemoteVideoUnavailable",i=>{let e=i.streamType==="sub"?"auxiliary":"main";this.renderDumpTab(i.userId,"remote",e,"unpublish")});c(this,"handleRemoteAudioAvailable",i=>{this.renderDumpTab(i.userId,"remote","audio","publish")});c(this,"handleRemoteAudioUnavailable",i=>{this.renderDumpTab(i.userId,"remote","audio","unpublish")});c(this,"renderDumpTab",(i,e,t,r)=>{var a,d,l;let o={main:"video",auxiliary:"screen",audio:"audio"},n=(h,u)=>{var I,v,b;let m=document.createElement("div");m.innerText=`${h} - ${o[u]} - ${Re.DURATION}(s):`;let p=document.createElement("input");p.type="number",p.min="0",p.value="10",p.id=`dump_remote_${u}_${h}`;let g=document.createElement("button");g.innerText=Re.END_BUTTON,g.disabled=!0;let f=document.createElement("button");f.innerText=Re.DUMP_BUTTON,f.onclick=()=>{let w,N,q=Number(p.value);if(u==="audio")({download:w,onDumpEnd:N}=this.dumpAudio("remote",q,h));else{if(!this.isSupportDumpVideo())return;({download:w,onDumpEnd:N}=this.dumpVideo(u,"remote",q,h))}w&&(this.inactiveButton(f,Re.DUMPING_BUTTON),q>0?setTimeout(()=>{w==null||w(),this.activeButton(f,Re.DUMP_BUTTON)},q*1e3):(this.activeButton(g),g.onclick=()=>{g.onclick=null,w==null||w(),N==null||N(),this.activeButton(f,Re.DUMP_BUTTON),this.inactiveButton(g)}))},m.appendChild(p),m.appendChild(f),m.appendChild(g),m.style.cssText="padding:10px;";let T=document.createElement("div");return T.style.cssText="width:100%;display:flex;justify-content:center;border-top: 1px solid var(--DD-BORDER);",T.appendChild(m),(b=(v=(I=this._dialogNode)==null?void 0:I.shadowRoot)==null?void 0:v.querySelector(`.${rr}`))==null||b.appendChild(T),T};if(e==="remote")if(r==="publish"){let h=n(i,t);this.publishMap.set(`${i}-${e}-${t}`,h)}else{let h=this.publishMap.get(`${i}-${e}-${t}`);if(!h)return;(l=(d=(a=this._dialogNode)==null?void 0:a.shadowRoot)==null?void 0:d.querySelector(`.${rr}`))==null||l.removeChild(h),this.publishMap.delete(`${i}-${e}-${t}`)}});c(this,"handleStatistics",i=>{var l,h,u,m,p,g;let e=(i.bytesSent-this.prevBytesSent)/2,t=(i.bytesReceived-this.prevBytesReceived)/2;this.prevBytesSent=i.bytesSent,this.prevBytesReceived=i.bytesReceived;let r=(h=(l=this._dialogNode)==null?void 0:l.shadowRoot)==null?void 0:h.querySelector(`.${Bf}`);r.innerHTML=`rtt: ${i.rtt} ms upLoss: ${i.upLoss}% downLoss: ${i.downLoss}% <br>
63
+ \u2191 ${e/1e3} KB/s (${8*e/1e3} Kb/s) <br>
64
+ \u2193 ${t/1e3} KB/s (${8*t/1e3} Kb/s) <br>
65
+ `;let o=(m=(u=this._dialogNode)==null?void 0:u.shadowRoot)==null?void 0:m.querySelector(`.${Ac}`),n="";i.localStatistics.audio.bitrate&&(n=`<li>local audio: ${i.localStatistics.audio.bitrate} Kb/s audioLevel: ${i.localStatistics.audio.audioLevel.toFixed(5)}</li>`),i.localStatistics.video.length>0&&(n+=`${i.localStatistics.video.map(f=>`<li>local ${f.videoType} video: ${f.bitrate} Kb/s ${f.width}*${f.height} ${f.frameRate}fps</li>`).join("")}`),o.innerHTML=n===""?`${Re.NO_DATA}`:n;let a=(g=(p=this._dialogNode)==null?void 0:p.shadowRoot)==null?void 0:g.querySelector(`.${Cc}`),d="";i.remoteStatistics.length>0&&i.remoteStatistics.forEach(f=>{let T=`remote ${f.userId}:`;f.audio.bitrate>0&&(T+=`<li>audio: ${f.audio.bitrate} Kb/s audioLevel: ${f.audio.audioLevel.toFixed(5)}</li>`),f.video.length>0&&f.video.forEach(I=>{T+=`<li>${I.videoType} video: ${I.bitrate} Kb/s ${I.width}*${I.height} ${I.frameRate}fps</li>`}),d+=T}),a.innerHTML=d===""?`${Re.NO_DATA}`:d});c(this,"pad",i=>i<10?`0${i}`:`${i}`);this._core=i,this._log=e,this.dumpLocalVideoMap=t,this.dumpRemoteVideoMap=r,this.initCustomElements(),this.synchronizeLog(),this.installEvents()}initCustomElements(){this._isMobile=Cf();let i=document.createElement("trtc-basic-debug-dialog");document.body.appendChild(i);let e=i.shadowRoot;if(this._dialogNode=i,!e)return;this._switchNode=e.querySelector(`.${Sc}`),this._addEventListener(this._switchNode,"click",this.onSwitchClick.bind(this));let t=getComputedStyle(this._switchNode);this.switchPos.x=parseInt(t.right,10)||50,this.switchPos.y=parseInt(t.bottom,10)||100+Uh*50,this._isMobile?(this._switchNode.ontouchstart=this.onTouchStart.bind(this),this._switchNode.ontouchend=this.onTouchEnd.bind(this),this._switchNode.ontouchmove=this.onTouchMove.bind(this)):this._switchNode.onmousedown=this.onMouseDown.bind(this),this._maskNode=e.querySelector(`.${xh}`),this._addEventListener(this._maskNode,"click",this.onMaskClick.bind(this)),this._panelNode=e.querySelector(`.${Ic}`),e.querySelector(`.${vc}`).childNodes.forEach(b=>{switch(b.getAttribute("data-type")){case"go_bottom":this._addEventListener(b,"click",this.onGoBottomClick.bind(this));break;case"back_top":this._addEventListener(b,"click",this.onBackTopClick.bind(this));break;case"clear_log":this._addEventListener(b,"click",this.onClearLogClick.bind(this));break}}),this._logContentNode=e.querySelector(`.${Bh}`),this._networkContentNode=e.querySelector(`.${Bs}`),this._dumpContentNode=e.querySelector(`.${Ur}`),this._tabNodes=Array.from(e.querySelector(`.${Lh}`).children),this._tabNodes.forEach(b=>{this._addEventListener(b,"click",this.onTabClick.bind(this))}),this._toptabNodes=Array.from(e.querySelector(`.${Ph}`).children),this._toptabNodes.forEach(b=>{this._addEventListener(b,"click",this.onToptabClick.bind(this))});let o=e.querySelector("#trtc_upload");this._addEventListener(o,"click",this.onUploadClick.bind(this));let n=e.querySelector("#trtc_export");this._addEventListener(n,"click",this.onExportClick.bind(this));let a=e.querySelector("#trtc_hide");this._addEventListener(a,"click",this.onHideClick.bind(this));let d=e.querySelector(`#${yc} .dump`),l=e.querySelector(`#${yc} .end-dump`),h=Number(e.querySelector(`#${yc} input`).value);this._addEventListener(d,"click",this.getDumpButtonClickHandler.bind(this,d,l,h,"main","local"));let u=e.querySelector(`#${bc} .dump`),m=e.querySelector(`#${bc} .end-dump`),p=Number(e.querySelector(`#${bc} input`).value);this._addEventListener(u,"click",this.getDumpButtonClickHandler.bind(this,u,m,p,"auxiliary","local"));let g=e.querySelector(`#${Rc} button`);this._addEventListener(g,"click",()=>{let b=Number(e.querySelector(`#${Rc} input`).value),{download:w,onDumpEnd:N}=this.dumpAudio("local",b);if(!w){this.addInfoToBanner(Po,"Failed to dump, please check if the current user has started the audio");return}if(this.inactiveButton(g,Re.DUMPING_BUTTON),b>0)setTimeout(()=>{w(),this.activeButton(g,Re.DUMP_BUTTON)},b*1e3);else{let q=e.querySelector(`#${Rc} .end-dump`);this.activeButton(q),q.onclick=()=>{q.onclick=null,w(),N==null||N(),this.activeButton(g,Re.DUMP_BUTTON),this.inactiveButton(q)}}});let f=e.querySelector("#dump-remote-video-hook-userid"),T=e.querySelector("#dump-remote-video-hook-duration"),I=e.querySelector("#dump-remote-video-hook-mediaType"),v=e.querySelector("#dump-remote-video-hook-button");v.onclick=()=>{let b=Number(T.value);if(b<1){this.addInfoToBanner(Po,"duration at least 1s");return}let w=f.value;if(!w){this.addInfoToBanner(Po,"please input user id");return}w==="*"&&this.inactiveButton(v);let N=I.value,q=`remote_${w}_${N==="sub"?"auxiliary":N}`,$,te,se=y=>{if((y.userId===w||w==="*")&&y.streamType===N){if(this.addInfoToBanner(xr,`[${y.userId}_${N}] starting to dump video, duration: ${b}s`),{download:$,onDumpEnd:te}=this.dumpVideo(y.streamType==="sub"?"auxiliary":y.streamType,"remote",b,y.userId),!$)return;setTimeout(()=>{$==null||$(),te==null||te(),w!=="*"&&this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,se)},b*1e3)}};this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,se),this.addInfoToBanner(xr,`[${q}] waiting to dump video from ${w==="*"?"all remote users":`user ${w}`}, duration: ${b}s`)}}synchronizeLog(){this._core.loggerManager.getQueue().forEach(e=>{this.updateLog(e)})}isSupportDumpVideo(){return!this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&!this._core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED?(this.addInfoToBanner(Po,"Current browser does not support dumping video"),!1):!0}_addEventListener(i,e,t,r){i&&(i.addEventListener(e,t,r),this.eventMap.set(i,{type:e,listener:t}))}_removeEventListener(){this.eventMap.forEach(({type:i,listener:e},t)=>{t&&t.removeEventListener(i,e)}),this.eventMap.clear(),this._switchNode&&(this._switchNode.onmousedown=null,this._switchNode.ontouchmove=null,this._switchNode.ontouchstart=null,this._switchNode.ontouchend=null)}closeDialog(){this.uninstallEvents(),this._removeEventListener(),this._dialogNode&&(document.body.removeChild(this._dialogNode),this._dialogNode=null)}updateLog(i){var t;this._logList.push(i);let e=document.createElement("div");switch(e.classList.add(Pr),i.level){case 4:e.classList.add(Vf);break;case 2:e.classList.add(Pf);break;case 3:e.classList.add(Uf);break;case 1:e.classList.add(Lf);break;default:break}e.textContent=i.log,this._showLogType!=="all"&&!e.classList.contains(`${Pr}_${this._showLogType}`)&&(e.style.display="none"),(t=this._logContentNode)==null||t.appendChild(e),this.addHelper(e)}getDumpButtonClickHandler(i,e,t,r,o){if(!this.isSupportDumpVideo())return;let{download:n,onDumpEnd:a}=this.dumpVideo(r,o,t);if(n){this.addInfoToBanner(xr,`[${o}_${r}] starting to dump...`),this.inactiveButton(i,Re.DUMPING_BUTTON),t>0?setTimeout(()=>{n(),this.activeButton(i,Re.DUMP_BUTTON)},t*1e3):(this.activeButton(e),e.onclick=()=>{e.onclick=null,a==null||a(),n(),this.activeButton(i,Re.DUMP_BUTTON),this.inactiveButton(e)});return}this.addInfoToBanner(xr,`[${o}_${r}] waiting to dump...`);let d=({track:l})=>{if(l.room===this._core.room&&l.streamType===r){this.addInfoToBanner(xr,`[${o}_${r}] starting to dump`),o==="local"&&this._core.innerEmitter.off("104",d);let{download:h,onDumpEnd:u}=this.dumpVideo(r,o,t);if(!h)return;t>0?setTimeout(()=>{h(),this.activeButton(i,Re.DUMP_BUTTON)},t*1e3):(this.activeButton(e),e.onclick=()=>{e.onclick=null,u==null||u(),h(),this.activeButton(i,Re.DUMP_BUTTON),this.inactiveButton(e)})}};d.bind(this),o==="local"&&this._core.innerEmitter.on("104",d),this.inactiveButton(i,Re.DUMPING_BUTTON)}onSwitchClick(){if(this._hasMove){this._hasMove=!1;return}this._showDialog?this.hideDialog():(this._isMobile&&(this._maskNode.style.display="block"),this._panelNode.style.display="block",this._switchNode.style.display="none",this._showDialog=!0,this.logContentGoBottom())}onTabClick(i){var r,o,n,a,d,l,h;let e=i.target;(r=this._tabNodes)==null||r.forEach(u=>{u.classList.remove(os)}),e.classList.add(os);let t=e.getAttribute("data-tab");t==="log"?((a=(n=(o=this._dialogNode)==null?void 0:o.shadowRoot)==null?void 0:n.querySelector(`.${Lr}`))==null||a.classList.add(Nc),this._logContentNode.style.display="block",this._networkContentNode.style.display="none",this._dumpContentNode.style.display="none",this.logContentGoBottom()):((h=(l=(d=this._dialogNode)==null?void 0:d.shadowRoot)==null?void 0:l.querySelector(`.${Lr}`))==null||h.classList.remove(Nc),t==="network"?(this._networkContentNode.style.display="block",this._logContentNode.style.display="none",this._dumpContentNode.style.display="none"):t==="dump"&&(this._dumpContentNode.style.display="block",this._networkContentNode.style.display="none",this._logContentNode.style.display="none"))}onToptabClick(i){var o,n;let e=i.target;(o=this._toptabNodes)==null||o.forEach(a=>{a.classList.remove(os)}),e.classList.add(os),this._showLogType=e.getAttribute("data-type");let t=(n=this._logContentNode)==null?void 0:n.querySelectorAll(`.${Pr}`),r=`${Pr}_${this._showLogType}`;t.forEach(a=>{a.classList.contains(r)||this._showLogType==="all"?a.style.display="block":a.style.display="none"}),this.logContentGoBottom()}onExportClick(){let i=this._logList.reduce((n,a)=>`${n+a.log}
66
+ `,""),e=new Blob([i],{type:"text/plain"}),t=document.createElement("a"),r=URL.createObjectURL(e);t.href=r;let o=`trtc_${this._core.room.sdkAppId===void 0?"EmptySdkAppId":this._core.room.sdkAppId}_${this._core.room.userId===void 0?"EmptyUserId":this._core.room.userId}_${this.formatStartDumpTime(+new Date)}.log`;t.download=o,t.style.display="none",document.body.appendChild(t),t.click(),URL.revokeObjectURL(r),document.body.removeChild(t),this.addInfoToBanner(xr,`Export success: The log file name is ${o}`),this._core.kvStatManager.addSuccessEvent({key:592703})}addInfoToBanner(i,e){var n,a;let t=(a=(n=this._dialogNode)==null?void 0:n.shadowRoot)==null?void 0:a.querySelector(`.${Dc}`),r=document.createElement("div");r.classList.add(xf);let o=i===xr?"\u{1F7E9}":i===wf?"\u{1F7E7}":"\u{1F7E5}";r.innerText=`${o} [${this.getCurrentTime()}] ${e}`,t.appendChild(r),t.scrollTop=t.scrollHeight}onUploadClick(){return A(this,null,function*(){var a,d;if(this.isUploading)return;this.isUploading=!0;let i=(d=(a=this._dialogNode)==null?void 0:a.shadowRoot)==null?void 0:d.querySelector("#trtc_upload");i.innerText="Uploading...",i==null||i.classList.add(".disable");let e=this._logList.reduce((l,h)=>`${l+h.log}
67
+ `,""),t=new Blob([e],{type:"text/plain"}),r=new FormData;r.append("file",t,"trtc.log"),r.append("sdkAppId",`${this._core.room.sdkAppId||"EmptySdkAppId"}`),r.append("userId",`${this._core.room.userId||"EmptyUserId"}`),fetch("https://service.trtc.qcloud.com/api/uploadLogFile",{method:"POST",body:r}).then(l=>l.json()).then(l=>{this.addInfoToBanner(l.type,l.message_en||"Upload Failed: Please use local export"),this.isUploading=!1,this._log.info(l.message_en),this._core.kvStatManager.addSuccessEvent({key:592704})}).catch(()=>{this.addInfoToBanner(Po,"Upload Failed: Please use local export"),this._log.info("Upload Failed: Please use local export"),this._core.kvStatManager.addFailedEvent({key:592704})}).finally(()=>{i.innerText=Re.UPLOAD_BUTTON,i==null||i.classList.remove(".disable"),this.isUploading=!1})})}onHideClick(){this.hideDialog()}onMaskClick(){this.hideDialog()}hideDialog(){this._isMobile&&(this._maskNode.style.display="none"),this._panelNode.style.display="none",this._switchNode.style.display="block",this._showDialog=!1}onBackTopClick(){var i,e,t;(t=(e=(i=this._dialogNode)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector(`.${Lr}`))==null||t.scrollTo(0,0)}onGoBottomClick(){this.logContentGoBottom()}onClearLogClick(){this._logList=[],this._logContentNode&&(this._logContentNode.innerHTML="")}logContentGoBottom(){var e,t;let i=(t=(e=this._dialogNode)==null?void 0:e.shadowRoot)==null?void 0:t.querySelector(`.${Lr}`);i==null||i.scrollTo(0,i==null?void 0:i.scrollHeight)}onMouseDown(i){i.preventDefault(),this.switchPos.startX=i.pageX,this.switchPos.startY=i.pageY,document.onmousemove=this.onMouseMove.bind(this),document.onmouseup=this.onMouseUp.bind(this)}onMouseMove(i){i.cancelable&&i.preventDefault(),this._hasMove=!0;let e=this.switchPos.x-(i.pageX-this.switchPos.startX),t=this.switchPos.y-(i.pageY-this.switchPos.startY);[e,t]=this.getSafeAreaXY(e,t),this._switchNode.style.right=`${e}px`,this._switchNode.style.bottom=`${t}px`,this.switchPos.endX=e,this.switchPos.endY=t}onMouseUp(){this.switchPos.startX=0,this.switchPos.startY=0,this.switchPos.x=this.switchPos.endX,this.switchPos.y=this.switchPos.endY,document.onmousemove=null,document.onmouseup=null}onTouchStart(i){this.switchPos.startX=i.touches[0].pageX,this.switchPos.startY=i.touches[0].pageY,this.switchPos.isTouchEnd=!1}onTouchEnd(){this.switchPos.isTouchEnd&&(this.switchPos.startX=0,this.switchPos.startY=0,this.switchPos.isTouchEnd=!1,this.switchPos.x=this.switchPos.endX,this.switchPos.y=this.switchPos.endY)}onTouchMove(i){if(i.touches.length<=0)return;let e=i.touches[0].pageX-this.switchPos.startX,t=i.touches[0].pageY-this.switchPos.startY,r=Math.floor(this.switchPos.x-e),o=Math.floor(this.switchPos.y-t);[r,o]=this.getSafeAreaXY(r,o),this._switchNode.style.right=`${r}px`,this._switchNode.style.bottom=`${o}px`,this.switchPos.endX=r,this.switchPos.endY=o,this.switchPos.isTouchEnd=!0,i.cancelable&&i.preventDefault()}getSafeAreaXY(i,e){let t=Math.max(document.documentElement.offsetWidth,window.innerWidth),r=Math.max(document.documentElement.offsetHeight,window.innerHeight);return i+this._switchNode.offsetWidth>t&&(i=t-this._switchNode.offsetWidth),e+this._switchNode.offsetHeight>r&&(e=r-this._switchNode.offsetHeight),i<0&&(i=0),e<20&&(e=20),[i,e]}hitTest(i){return i===this._core.room}installEvents(){this._core.innerEmitter.on("264",this.handleLog,this),this._core.innerEmitter.on("53",this.handleLeaveSuccess,this),this._core.innerEmitter.on("27",this.handleJoinSuccess,this),this._core.trtc.on(this._core.TRTC.EVENT.STATISTICS,this.handleStatistics,this),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_AUDIO_AVAILABLE,this.handleRemoteAudioAvailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_AUDIO_UNAVAILABLE,this.handleRemoteAudioUnavailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,this.handleRemoteVideoAvailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_UNAVAILABLE,this.handleRemoteVideoUnavailable),this._core.room.on("dump",this.handleDumpFromScriptTransform,this)}uninstallEvents(){this._core.innerEmitter.off("264",this.handleLog,this),this._core.innerEmitter.off("53",this.handleLeaveSuccess,this),this._core.innerEmitter.off("27",this.handleJoinSuccess,this),this._core.trtc.off(this._core.TRTC.EVENT.STATISTICS,this.handleStatistics,this),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_AUDIO_AVAILABLE,this.handleRemoteAudioAvailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_AUDIO_UNAVAILABLE,this.handleRemoteAudioUnavailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,this.handleRemoteVideoAvailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_UNAVAILABLE,this.handleRemoteVideoUnavailable),this._core.room.off("dump",this.handleDumpFromScriptTransform,this)}handleDumpFromScriptTransform(i){if(!i.isAudio)if(i.userId){let e=this.dumpRemoteVideoMap[`${i.userId}-${i.streamType}`];e&&(e.data.push(i.data),e.duration>0&&Date.now()-e.startTimestamp>e.duration*1e3&&e.onDumpEnd())}else{let e=i.streamType==="main"?"main":"sub",t=this.dumpLocalVideoMap[e];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}}inactiveButton(i,e){i.disabled=!0,e&&(i.innerText=e)}activeButton(i,e){i.disabled=!1,e&&(i.innerText=e)}handleLog(i){this.updateLog(i.log)}addHelper(i){let e=/((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g,t=yf,r=i.innerText;r=r.split(`
68
+ `).map(o=>{if(o=o.replace(/</g,"&lt;").replace(/>/g,"&gt;"),o.includes("failed"))return o.includes("on autoplay-failed")?o:`<span class='red' style="background:red; color:#fff;">${o}</span>`;if(o.includes("clientIp:")){let n=o.match(e);return n==null||n.forEach(a=>{o=o.replace(a,`<a href="javascript:void(0);" target=""><span class='ip' style="background:#e1dfdf">${a}</span></a>`)}),o}return o.includes("URL of current page")&&(o=o.replace(/URL of current page: (.+)/,'URL of current page: <a href="$1">$1</a>')),o}).join(`
69
+ `),t.forEach(o=>{if(i.innerText.includes(o)){let n="";n=typeof ss[o].tips=="function"?ss[o].tips(i.innerText):ss[o].tips,r=r.replace(new RegExp(`${Rf(o)}`,"gi"),`<span class="${aa}" style="background:${ss[o].color||"#e1dfdf"}; color: ${ss[o].textColor||"#000"}">${o}
70
+ <span class="tooltiptext tooltip-top">${n}</span>
71
+ </span>`)}}),i.innerHTML=r}getCurrentTime(){let i=new Date,e=this.pad(i.getHours()),t=this.pad(i.getMinutes()),r=this.pad(i.getSeconds());return`${e}:${t}:${r}`}dumpVideo(i,e,t,r){let o=Date.now(),n=this.formatStartDumpTime(o),a=[],d=`${e}_${r}_${i}`,l=()=>{if(a.length===0){this.addInfoToBanner(Po,`[${d}] dump failed. Reason: data is empty`);return}let u;i==="main"?u="video":i==="auxiliary"&&(u="screen");let m=URL.createObjectURL(new Blob(a)),p=document.createElement("a"),g=e==="local"?`local_${u}_${n}.h264`:`remote-${r}_${u}_${n}.h264`;p.href=m,p.download=g,p.style.display="none",document.body.appendChild(p),p.click(),URL.revokeObjectURL(m),p.remove(),this.addInfoToBanner(xr,`[${d}] dump success. File name is: ${g}`)},h;if(e==="local"){if(!this.hasLocalTrack(i,"video"))return{};h=()=>{delete this.dumpLocalVideoMap[i==="auxiliary"?"sub":"main"]},this.dumpLocalVideoMap[i==="auxiliary"?"sub":"main"]={startTimestamp:o,data:a,duration:t,onDumpEnd:h}}if(e==="remote"&&r){if(h=()=>{delete this.dumpRemoteVideoMap[`${r}-${i}`]},this.dumpRemoteVideoMap[`${r}-${i}`])return this.addInfoToBanner(wf,`[${d}] dump already exists.`),{};this.dumpRemoteVideoMap[`${r}-${i}`]={startTimestamp:o,data:a,duration:t,onDumpEnd:h}}return{download:l,onDumpEnd:h}}hasLocalTrack(i,e){for(let t of this._core.room.localTracks)if(t.streamType===i&&t.kind===e)return!0;return!1}dumpAudio(i,e,t){var q,$,te;let r=null,o=[],n=[],a=[],d=[],l=[],h=[],u=[],m=new AbortController,p=Date.now(),g=this.formatStartDumpTime(p),f=this._core.room.audioManager._localAudioPipline,T=this._core.room.audioManager._localScreenAudioPipeline,I,v,b=({data:se})=>{a[0]=a[0]?a[0].concat(se):[se]},w=({room:se,data:y,type:G})=>{if(this.hitTest(se)){if(G==="dump"){if(d[0]=d[0]?d[0].concat(y.captureInput):y.captureInput,d[1]=d[1]?d[1].concat(y.playInput):y.playInput,!I)I=y.startTime,v=y.startTime;else{let j=y.startTime-I,Ce=y.endTime-y.startTime;if(j>30||Ce>30){let ee=function(he){if(typeof he!="number"||he<0)return"0\u6BEB\u79D2";let V=[],P=Math.floor(he/6e4),_e=he%6e4;P>0&&V.push(`${P}\u5206`);let ae=Math.floor(_e/1e3);return _e%=1e3,(ae>0||V.length)&&V.push(`${ae}\u79D2`),(_e>0||!V.length)&&V.push(`${_e}\u6BEB\u79D2`),V.join("")};var E=ee;let O=y.startTime-v,Ne=I-v;u.push(`${y.startTime} ${ee(O)}~${ee(Ne)} ${j} ${Ce}`)}I=y.startTime}h.push(y.startTime)}G==="dump-screen-audio"&&(l[0]=l[0]?l[0].concat(y.captureInput):y.captureInput,l[1]=l[1]?l[1].concat(y.playInput):y.playInput)}};if(i==="local"){let{sampleRate:se}=this._core.room.audioManager.audioContext;if(!this._core.room.audioManager.hasAudioTrack&&!this._core.room.audioManager.hasScreenAudioTrack)return{};if(f!=null&&f.source.node&&(o.push(f.source.node),n.push(`local_audio_raw_capture-${se}-${f.source.node.channelCount}`)),((q=f==null?void 0:f.audioProcessor)!=null&&q.node||T!=null&&T.audioProcessor.node)&&(this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!0}),this._core.innerEmitter.on("265",w),($=f==null?void 0:f.audioProcessor)!=null&&$.node&&(o.push(f.audioProcessor.node),n.push(`local_audio_audioProcessor_processed-${se}-${f.audioProcessor.node.channelCount}`)),T!=null&&T.audioProcessor.node&&(o.push(T.audioProcessor.node),n.push(`screen_audio_audioProcessor_processed-${se}-${T.audioProcessor.node.channelCount}`))),f!=null&&f.denoiser.node&&(o.push(f.denoiser.node),n.push(`local_audio_denoiser_processed-${se}-${f.denoiser.node.channelCount}`)),this._core.room.audioManager.mixWeight>1&&(f!=null&&f.stream)){let y=this._core.room.audioManager.audioContext.createMediaStreamSource(f.stream);y.channelCount=1,o.push(y),n.push(`local_audio_destination-${se}-${y.channelCount}`)}}else if(i==="remote"&&t!==void 0){let se=(te=this._core.room.remotePublishedUserMap.get(t))==null?void 0:te.remoteAudioTrack;if(!(se!=null&&se.mediaTrack))return{};let y=this._core.createAudioNode(se.mediaTrack);o.push(y),n.push(`remote_${t}`)}let N=()=>A(this,null,function*(){var j,Ce,O,Ne,ee;let se=new Mf.default;for(let he=0;he<n.length;he++)se.file(`${n[he]}.pcm`,new Blob(a[he]));if((j=d==null?void 0:d[0])!=null&&j.length&&se.file("audioProcessor_input_capture.pcm",new Blob(d[0])),(Ce=d==null?void 0:d[1])!=null&&Ce.length&&se.file("audioProcessor_input_playback.pcm",new Blob(d[1])),(O=l==null?void 0:l[0])!=null&&O.length&&se.file("audioProcessor_screen_audio_input_capture.pcm",new Blob(l[0])),(Ne=l==null?void 0:l[1])!=null&&Ne.length&&se.file("audioProcessor_screen_audio_input_playback.pcm",new Blob(l[1])),h!=null&&h.length){let he=h.reduce((V,P)=>`${V}
72
+ ${P}`);se.file("audioProcessor_handle_timestamp.txt",new Blob([he]))}if(u!=null&&u.length){let he=u.reduce((V,P)=>`${V}
73
+ ${P}`);se.file("audioProcessor_big_gap_data.txt",new Blob([he]))}let y=yield se.generateAsync({type:"blob"}),G=URL.createObjectURL(y),E=document.createElement("a");E.href=G,E.download=`${i}-audio-${g}.zip`,E.style.display="none",document.body.appendChild(E),E.click(),URL.revokeObjectURL(G),E.remove(),this.addInfoToBanner(xr,`Dump success, file name is: ${i}-${g}.zip`),this._core.trtc.off(ne.AUDIO_FRAME,b),this._core.innerEmitter.off("265",w),((ee=f==null?void 0:f.audioProcessor)!=null&&ee.node||T!=null&&T.audioProcessor.node)&&this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!1}),r&&clearTimeout(r),m.abort("download")});return e>0&&(r=Number(setTimeout(()=>{m.abort("timeout")},e*1e3))),o.length>0&&this._core.startGetPCM(o).then(se=>se.pipeTo(new WritableStream({write(y){y.forEach((G,E)=>{a[E]=a[E]?a[E].concat(G[0]):[G[0]]})}}),m).catch(()=>N)),{download:N,onDumpEnd:()=>{m.abort("timeout")}}}formatStartDumpTime(i){let e=new Date(i),t=e.getFullYear(),r=this.pad(e.getMonth()+1),o=this.pad(e.getDate()),n=this.pad(e.getHours()),a=this.pad(e.getMinutes()),d=this.pad(e.getSeconds()),l=-e.getTimezoneOffset(),h=Math.floor(Math.abs(l)/60),u=Math.abs(l)%60,m=l>=0?"+":"-";return`${t}-${r}-${o}T${n}-${a}-${d}${m}${this.pad(h)}-${this.pad(u)}`}};J([ra(300,()=>"export")],da.prototype,"onExportClick",1),J([ra(300,()=>"upload")],da.prototype,"onUploadClick",1);var Ff=da;var gS=0;var Uo=class Uo{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dumpLocalVideoMap",{});c(this,"dumpRemoteVideoMap",{});c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++gS}`}),this.log.info("created")}getName(){return Uo.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 A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return A(this,arguments,function*({forceOpen:i}){M(i)&&(i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){if(!this.dialog)try{this.dialog=new Ff(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(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):kh,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Oh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return kh({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Oh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};c(Uo,"Name","Debug"),c(Uo,"autoStart",!0),J([Gt({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Uo.prototype,"loadScript",1);var kc=Uo;var Hf=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Oc=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=We(e,ge.INIT),this.stopOB=Vt(),this.startOB=Vt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=Vt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),He(l,St(this.stopOB),it(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Hf(this.type),error:h}),d>4?this.startOB.error(h):this.startOB.next(d+1)})),He(l,Dr(1),sh(Yn))};He(this.startOB,Xn(0),yo(a),St(this.stopOB),it(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Hf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return Nr()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},ES={type:"object"},la=class la{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return la.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return la.Name}getValidateRule(i){return ES}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Oc(this.core,t,i);return He(r.trackDoneOB,Dr(1),it(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Oc(this.core,i.track,i))}}};c(la,"Name","TRTCAudioDecoder");var ua=la;var Gf=0,ha=new Set,At=null;Zc(If);po.checkStorage();nu();var TS={RtcError:ue,ErrorCode:fe,ErrorCodeDictionary:Ri},Ie=class Ie extends Wf.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",z.createLogger({id:`t${++Gf}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"_getPCMAbortCtrl");this._room=new e(Z({logger:this._log,frameWorkType:Ie.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(_c,t.assetsPath),this._use(pc,t.assetsPath),this._use(Ec,t.assetsPath),this._use(ua,t.assetsPath||ba),this._use(kc),t.enableSEI&&xn&&this._use(Tc),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(ne.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new ue({code:fe.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Tf(this,"trtc")}static create(e){}static _create(e,t){nf();let r=new Ie(e,t||{});return ha.add(r),r}get room(){return this._room}_listenEvents(){vt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(ne.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(ne.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(ne.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(ne.ERROR,ue.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(ne.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=de(Z({},e),{uplinkRTT:Math.min(e.uplinkRTT,an),downlinkRTT:Math.min(e.downlinkRTT,an)});this.emit(ne.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{vt(r,r).add("player-state-changed",o=>{let n=de(Z({},o),{userId:e.userId});r.kind===S.VIDEO&&(n.streamType=is(r.streamType)),this.emit(r.kind===S.AUDIO?ne.AUDIO_PLAY_STATE_CHANGED:ne.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===H.PLAY_NOT_ALLOWED&&this.emit(ne.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{at(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?ne.REMOTE_VIDEO_AVAILABLE:ne.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?ne.REMOTE_AUDIO_AVAILABLE:ne.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?ne.REMOTE_VIDEO_AVAILABLE:ne.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(ne.SEI_MESSAGE,de(Z({},e),{streamType:is(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(ne.ERROR,new ue({code:fe.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,d,l,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,an),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/ai},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ai},video:m.msg_video_status.map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_dec_fps,videoType:t[p.uint32_video_stream_type]}))}))};this.emit(ne.STATISTICS,r)}).add("custom-message",e=>{this.emit(ne.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(ne.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},e),{streamType:is(e.streamType)}))}),vt(this,ft).add("audioInputAdded",e=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),At&&At.deviceId===nn){let t=(yield Yr()).find(r=>r.deviceId===nn);t&&At.groupId!==t.groupId&&(At=t,this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Yr())[0];if(!t||!At||At.groupId===t.groupId)return;let r=At.deviceId===e.deviceId,o=At.deviceId===nn&&At.deviceId===t.deviceId;(r||o)&&(At=t,this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||ba)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Ef.call(this,{TRTC:Ie,room:this._room,errorModule:TS,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var d,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,Qe(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Ie.frameWorkType),this._checkTrackToPublish(),Ah.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return A(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(){at(this),this.removeAllListeners(),this._room.destroy(),ha.delete(this),ha.size===0&&Ah.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),x.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(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 ti(this._room.audioManager),a={},d={muted:!0};o&&(M(o.microphoneId)?M(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&De(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),M(o.profile)||(Oe(o.profile)?Da[o.profile]&&n.setProfile(Da[o.profile]):n.setProfile(o.profile)),De(o.earMonitorVolume)&&(d.muted=!(o.earMonitorVolume>0),d.volume=o.earMonitorVolume),M(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),M(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),M(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(ne.ERROR,new ue({code:fe.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=ue.convertFrom(l.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},l),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),M(r)||n.setMute(r),vt(n,n).add("player-state-changed",l=>{this.emit(ne.AUDIO_PLAY_STATE_CHANGED,de(Z({},l),{userId:""}))}),this.listeners(ne.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:l})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=de(Z({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n})})}updateLocalAudio(e){return A(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):M(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),M(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),M(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!M(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),M(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Li(this._localAudioConfig,e)})}stopLocalAudio(){return A(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),at(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return A(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 Nt(this._room.videoManager),d={},l={};Qe(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?d.deviceId=n.cameraId:M(n.useFrontCamera)?M(n.videoTrack)||(d.customSource=n.videoTrack):d.facingMode=n.useFrontCamera?S.FACING_MODE_USER:S.FACING_MODE_ENVIRONMENT,n.qosPreference&&(d.contentHint=ia(n.qosPreference)),M(n.profile)||(Oe(n.profile)?si[n.profile]&&a.setProfile(si[n.profile]):a.setProfile(n.profile)),M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror),M(n.small)||(On()?Oe(n.small)?a.small=si[n.small]:n.small===!0?a.small=si["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",h=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},h),{streamType:is(h.streamType)}))}),a.on("5",h=>{this.emit(ne.ERROR,new ue({code:fe.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=ue.convertFrom(h.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(d),M(o)||(yield a.setMute(o)),vt(a,a).add("player-state-changed",h=>{this.emit(ne.VIDEO_PLAY_STATE_CHANGED,de(Z({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=de(Z({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return A(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(M(n.profile)||(Oe(n.profile)?si[n.profile]&&this._localVideoTrack.setProfile(si[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&M(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):M(n.useFrontCamera)?M(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?S.FACING_MODE_USER:S.FACING_MODE_ENVIRONMENT),M(n.fillMode)||(a.objectFit=n.fillMode),M(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(ia(n.qosPreference)),n.small){let d=!this._localVideoTrack.small;On()?(n.small===!0?this._localVideoTrack.small=si["120p"]:Oe(n.small)?this._localVideoTrack.small=si[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&&!M(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),M(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Li(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),at(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){var u;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new jt(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=ue.convertFrom(m.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},m),{error:p}))}),n.once("first-video-frame",m=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},m),{streamType:is(m.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,d={},l={};o&&(M(o.profile)||(Oe(o.profile)?ka[o.profile]&&n.setProfile(ka[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(d.systemAudio=!0,d.echoCancellation=o.echoCancellation,d.noiseSuppression=o.noiseSuppression,d.autoGainControl=o.autoGainControl),M(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(d.videoTrack=o.videoTrack),o.audioTrack&&(d.audioTrack=o.audioTrack),o.captureElement&&(d.captureElement=o.captureElement),o.preferDisplaySurface&&(d.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(d.contentHint=ia(o.qosPreference)));let h=yield n.capture(d);if(n.mediaTrack.addEventListener(S.ENDED,()=>{this._stopScreenShare(),this.emit(ne.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new Yi(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),vt(n,n).add("player-state-changed",m=>{this.emit(ne.VIDEO_PLAY_STATE_CHANGED,de(Z({},m),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let m=[n];if(a){m.push(a);let{echoCancellation:p}=((u=a.mediaTrack)==null?void 0:u.getSettings())||{};if(p===!1){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,screenAudio:!0,localAudio:!1})}catch(g){this._log.warn("start audioProcessor plugin failed: ",g)}}}this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=de(Z({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(M(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=ia(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!M(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}),Li(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},h=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror),M(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!M(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!M(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var T,I;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,d=this._remoteVideoConfigMap.get(a);if(!d||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u!=null&&u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:m}=d;o==="main"&&n&&!M(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:h,prevConfig:m}),Li(m,e);let p=M(n==null?void 0:n.receiveWhenViewVisible)?(T=m.option)==null?void 0:T.receiveWhenViewVisible:n.receiveWhenViewVisible,g=M(t)?m.view:t,f=M(n==null?void 0:n.viewRoot)?(I=m.option)==null?void 0:I.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:g,receiveWhenViewVisible:p,viewRoot:f})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return A(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return A(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return A(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return A(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===Ie.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(Ie.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(Ie.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{pf.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===Ie.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(Oe(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return A(this,null,function*(){(yield Yr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),At=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 A(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),d=De(a)?a:100;o.volume=d,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),He(We(n,"decode-failed"),St(We(n,ge.INIT)),it(()=>{this.startPlugin(ua.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),n.outMediaTrack&&x.emit("266",{room:this.room,type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return A(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),x.emit("266",{room:this.room,type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;He(We(e,"decode-failed"),St(We(e,ge.INIT)),ah(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Ms(We(e,"decode-downgrade-state-changed")),it(n=>{o=n.state,this.emit(ne.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,de(Z({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return A(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),M(e)&&o&&o.view&&!Ys(t)){let a=Ks(o.view);a.length>0&&(yield r.play(a,t))}if(!M(e)){let a=Ks(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return A(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(M(e.muted)||t.setPlayerMute(e.muted),M(e.volume)||t.setAudioVolume(e.volume/100),t instanceof ti&&t.mediaTrack){let n=e.muted===!1&&!M(e.volume)&&e.volume>0?"add":"remove";x.emit("266",{room:this.room,type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ci){let n=e.muted?0:e.volume;if(M(n))return;x.emit("266",{room:this.room,type:"update_volume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(ne.TRACK,{userId:r,streamType:is(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o,n;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack)){e.push(this._localScreenAudioTrack);let{echoCancellation:a}=((n=this._localScreenAudioTrack.mediaTrack)==null?void 0:n.getSettings())||{};if(a===!1){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,screenAudio:!0,localAudio:!1})}catch(d){this._log.warn("start audioProcessor plugin failed: ",d)}}}if(e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(M(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${is(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||tt(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(p=>{l.set(p.target,p.isIntersecting),e.log.info(`view ${p.target.id} is${p.isIntersecting?"":" not"} visible`)}),clearTimeout(h),h=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(Ks(t));l.forEach((m,p)=>{u.has(p)||(a.unobserve(p),l.delete(p))}),u.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Sf(this),this._room.remotePublishedUserMap.forEach(e=>{at(e.remoteAudioTrack),at(e.remoteVideoTrack),at(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(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),at(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!At||Ao(At))&&(this._initActiveSpeaker(),x.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(At&&!Ao(At))this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:At});else{let e=yield Yr();e[0]&&!Ao(e[0])?(At=e[0],this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):x.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:de(Z({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),Q.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),Q.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){z.setLogLevel(e),M(t)||(t?z.enableUploadLog():z.disableUploadLog())}static isSupported(){return Td()}static getCameraList(e=!0){return ei(e)}static getMicrophoneList(e=!0){return Wt(e)}static getSpeakerList(e=!0){return Yr(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(ze&&(e===ci.SPEAKER||e===ci.HEADSET)){let r=yield Ie.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;ha.forEach(n=>A(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Yr()).forEach(r=>{r.deviceId===e&&(ha.forEach(o=>{o._setCurrentSpeaker(e),o.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),At=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Cs.version=a),e){case"count":Cs.addCount({key:t,useUV:n});break;case"enum":Cs.addEnum({key:t,value:r,useUV:n});break;case"number":Cs.addNumber({key:t,value:r,split:o});break}}};c(Ie,"_loggerManager",z),c(Ie,"EVENT",ne),c(Ie,"ERROR_CODE",fe),c(Ie,"TYPE",ci),c(Ie,"frameWorkType",30),J([Xe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],Ie.prototype,"use",1),J([Ot(It.TRTC.enterRoom),es("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),be(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Xe()],Ie.prototype,"enterRoom",1),J([Xe()],Ie.prototype,"exitRoom",1),J([Ot(It.TRTC.switchRole),Us("room",{merge:(e,t)=>t}),Xe()],Ie.prototype,"switchRole",1),J([Xe()],Ie.prototype,"destroy",1),J([Ot(It.TRTC.startLocalAudio),es("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),Xe()],Ie.prototype,"startLocalAudio",1),J([Ot(It.TRTC.updateLocalAudio),Us("audio",{debounce:{delay:200,getKey:()=>`${Gf}-localAudio`,isNeedToDebounce:e=>{var t;return!M((t=e.option)==null?void 0:t.captureVolume)}}}),Xe()],Ie.prototype,"updateLocalAudio",1),J([ts("audio"),Xe()],Ie.prototype,"stopLocalAudio",1),J([Ot(It.TRTC.startLocalVideo),es("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),Xe()],Ie.prototype,"startLocalVideo",1),J([Ot(It.TRTC.updateLocalVideo),Us("video"),Xe()],Ie.prototype,"updateLocalVideo",1),J([ts("video"),Xe()],Ie.prototype,"stopLocalVideo",1),J([Ot(It.TRTC.startScreenShare),es("screen",()=>!0),Xe()],Ie.prototype,"startScreenShare",1),J([Ot(It.TRTC.updateScreenShare),Us("screen"),Xe()],Ie.prototype,"updateScreenShare",1),J([Xe()],Ie.prototype,"stopScreenShare",1),J([Ot(It.TRTC.startRemoteVideo),es(e=>`v${e.userId}${e.streamType}`,()=>!0),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"startRemoteVideo",1),J([Ot(It.TRTC.updateRemoteVideo),Us(e=>`v${e.userId}${e.streamType}`),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"updateRemoteVideo",1),J([Ot(It.TRTC.stopRemoteVideo),be(e=>function(t){return A(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"stopRemoteVideo",1),J([ts(e=>`v${e.userId}${e.streamType}`)],Ie.prototype,"_stopRemoteVideo",1),J([Ot(...It.TRTC.muteRemoteAudio),Xe({getRemoteId:e=>e})],Ie.prototype,"muteRemoteAudio",1),J([gh(...It.TRTC.setRemoteAudioVolume),ra(200,e=>e),Xe({getRemoteId:e=>e})],Ie.prototype,"setRemoteAudioVolume",1),J([hc("start"),Ut(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),es((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Xl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],Ie.prototype,"startPlugin",1),J([hc("update"),Us((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ql[e.getName()]})],Ie.prototype,"updatePlugin",1),J([hc("stop"),ts((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Yl[e.getName()]})],Ie.prototype,"stopPlugin",1),J([gh(...It.TRTC.enableAudioVolumeEvaluation)],Ie.prototype,"enableAudioVolumeEvaluation",1),J([Xe()],Ie.prototype,"getVideoSnapshot",1),J([Xe()],Ie.prototype,"_setCurrentSpeaker",1),J([es(e=>`a${e.userId}`,()=>!0)],Ie.prototype,"_startRemoteAudio",1),J([be(e=>function(t){return A(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(de(Z({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),ts(e=>`a${e.userId}`)],Ie.prototype,"_stopRemoteAudio",1),J([ts("room")],Ie.prototype,"_exitRoom",1),J([ts("screen")],Ie.prototype,"_stopScreenShare",1),J([Ot(...It.TRTC.sendSEIMessage),lh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Ie.prototype,"sendSEIMessage",1),J([Ot(It.TRTC.sendCustomMessage),lh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ie.prototype,"sendCustomMessage",1),J([Ot(It.TRTC.create)],Ie,"_create",1);var $h=Ie,ma=$h;var Fh=class{constructor(){c(this,"_set",new Set);x.on(B.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 SS(){return A(this,null,function*(){let s,i;try{let u=yield Wt();s=u&&u.length}catch(u){}try{let u=yield ei();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Wi.basis(),d={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:d,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Me.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),Me.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function zf(){return be(s=>{let i=new Fh;return function(e,t,r){return A(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 X({code:H.INVALID_OPERATION,message:pe({key:me.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new X({code:H.INVALID_OPERATION,message:pe({key:me.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}`),x.emit(B.JOIN_START,{room:this,roomId:o,params:e});let n=Jt.getEnv();n||(n=ar.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Oa.OLD_CLOUD_LADDER)?n=ar.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Oa.WEBRTC)&&(n=ar.WEBRTC))),Me.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Wi.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,SS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Jt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Jt.performanceNow(),x.emit(B.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&Me.uploadEvent({log:`stat-conv-${Number(Ti)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),x.emit(B.JOIN_FAILED,{room:this,error:a}),a}})}})}var jf=()=>be(s=>function(...i){return A(this,null,function*(){x.emit(B.LEAVE_START,{room:this}),yield s.call(this,...i),x.emit(B.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Jf(){return be(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xf=gt(Mt());var rt={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var bi={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},qf=[bi.UPDATE_REMOTE_MUTE_STAT,bi.UPLINK_NETWORK_STATS,bi.USER_LIST_RES,bi.MUTE_RESULT,bi.SERVER_FIRST_PACKAGE_RECEIVED,bi.RECEIVE_CUSTOM_MSG],Ee={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"},ve={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var wc=new Set;function Qf(s){let i=[...wc.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Vo=class extends Xf.default{constructor(e){var r,o,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-wc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,wc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=z.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return A(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=le();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 _s(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?S.BACKUP:S.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,d)=>{o.onclose=d,o.onerror=d,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?S.MAIN:S.BACKUP),d(new X({code:H.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===S.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(rt.SETUP_FAILED,new X({code:H.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(S.MAIN),this.unbindAndCloseSocket(S.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(rt.SETUP_FAILED,new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=ln(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(bi),d=Object.keys(bi)[n.indexOf(r)],l=Ee[d]||r;switch(qf.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case bi.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&gm(o.svrTime),this._log.info(`ChannelSetup Success ${le()-this._connectStartTime}`),Q.addSuccessEvent({key:521701,cost:le()-this._connectStartTime}),this._connectStartTime=-1,this.emit(rt.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:pe({key:me.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),Q.addFailedEvent({key:521701,error:h}),this.emit(rt.SETUP_FAILED,h)}break}case bi.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return A(this,null,function*(){try{if(!this.room.joinParams)return;yi(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?S.MAIN:S.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return A(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:ve.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:Ee.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),Q.addSuccessEvent({key:521702,cost:le()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(Q.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+=ln(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,h)=>{let u=setTimeout(()=>{this.off(o,p);let f=new X({code:H.API_CALL_TIMEOUT,message:pe({key:me.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),h(f)},r),m=Date.now(),p=f=>{f.data.seq===g&&(clearTimeout(u),this.off(o,p),d&&(f.data.receiveTime=Date.now()),l(f))};this.on(o,p);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ui({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(rt.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),wc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(S.MAIN),this.unbindAndCloseSocket(S.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(Ee.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Ee.JOIN_ROOM_RESULT,t))};this.on(Ee.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(rt.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(rt.CONNECTED):e==="DISCONNECTED"&&this.emit(rt.DISCONNECTED))}};J([Gt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Vo.prototype,"connect",1);var Yf=gt(Mt());var Hh=0,Gh=!1,Mc=new Set,AS=s=>Hh>2&&!Gh&&Mc.size===0&&s,Wh=!1,$t=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new Yf.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=z.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=le())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,Q.addSuccessEvent({key:521705,cost:Math.min(le()-this._prevTime,30*1e3)})):this._isReconnecting&&Q.addSuccessEvent({key:521706,cost:le()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,Q.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&Q.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(),Mc.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 X({code:H.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return hi;let i=null;if(this._isUplink){if(!Qr()||this._peerConnection.getSenders().length===0)return hi;i=this._peerConnection.getSenders()[0].transport}else{if(!Rs()||this._peerConnection.getReceivers().length===0)return hi;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:hi}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===Je.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Je.FAILED||i.target.connectionState===Je.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new X({message:r,code:H.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===Je.CONNECTED||i.target.connectionState===Je.COMPLETED)&&(this.logSelectedCandidate(),Me.logSuccessEvent({userId:this._room.userId,eventType:Ft.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Hh=0,Gh=!1,Wh=!0,Mc.add(this)):Mc.delete(this),x.emit(B.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 A(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Xr(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 X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{x.off(B.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new X({code:H.API_CALL_TIMEOUT,message:"connection timeout"});Hh+=1,AS(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this._emitter.emit("firewall-restriction")),e(a)},on);x.on(B.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(rt.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=dr()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new X({code:this._isUplink?H.UPLINK_RECONNECTION_FAILED:H.DOWNLINK_RECONNECTION_FAILED,message:pe({key:this._isUplink?me.UPLINK_RECONNECTION_FAILED:me.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(rt.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)}};J([zt(521712,!1)],$t.prototype,"setOffer",1),J([zt(521713,!1)],$t.prototype,"setAnswer",1);var qh=gt(Jh());var et=function(s){return qh.default.parse(s)},li=function(s){return qh.default.write(s)},o_=function(s){let i=et(s);return i.media.forEach(e=>{e.type===S.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),li(i)};function n_(s){let i=et(s);return i.media.forEach(e=>{var t,r;if(e.type===S.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),li(i)}function xc(s){return Object.keys(s).filter(i=>s[i])}var $o=class $o extends $t{constructor(e){super(de(Z({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ci(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new er(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Do(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 ur(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===S.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===sn?S.MAIN:S.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=S.AUDIO;r.kind===S.VIDEO&&(n=o===S.MAIN?S.VIDEO:S.AUXILIARY);let a=this.remoteAudioTrack;n===S.VIDEO?a=this.remoteVideoTrack:n===S.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
74
+ `),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,d]=o[n];t.splice(a+n,0,d)}return t.join(`\r
75
+ `)}addSPSDescription(e){let t=et(e);return t.media.forEach(r=>{r.type===S.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),li(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=et(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),li(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return A(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Je.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===Je.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 X({code:H.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return A(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=Z({},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} [${xc(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=ve.UNSUBSCRIBE,n=Ee.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=ve.SUBSCRIBE_CHANGE,n=Ee.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new X({code:a.code,message:pe({key:me.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return A(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return A(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:ve.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:Ee.SUBSCRIBE_RESULT,timeout:dl});if(!this._peerConnection){let a=new X({code:H.INVALID_OPERATION,message:pe({key:me.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return A(this,null,function*(){let e={voiceActivityDetection:!1};Yt()&&this._sdpSemantics===Gr?(this._peerConnection.addTransceiver(S.AUDIO,{direction:ke.RECVONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:ke.RECVONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:ke.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield Ed();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=n_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=o_(t.sdp),this._sdpSemantics===Gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return A(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===cs)throw new X({code:H.NOT_SUPPORTED_H264,message:pe({key:me.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new X({code:t,message:pe({key:me.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{et(e).media.forEach(r=>{if(r.ssrcs)if(r.type===S.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(sn)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(sn)}),n=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(rl)});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 A(this,null,function*(){if(!(Ct($o.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=pi(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}};J([be(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],$o.prototype,"subscribe",1),J([zt(521717,!1)],$o.prototype,"unsubscribe",1),J([Ut($t.prototype.afterConnect),xd($t.prototype.beforeConnect)],$o.prototype,"connect",1);var Xh=$o,Qh=Xh;var d_={voiceActivityDetection:!1},Fo=class Fo extends $t{constructor(e){super(de(Z({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});c(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Hi()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===S.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return A(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(),Yt()?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 A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),d&&a.addTrack(d);let h=this._peerConnection.getTransceivers();if(h.length===0)this._peerConnection.addTransceiver(l||S.AUDIO,{direction:ke.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?S.VIDEO:d||S.VIDEO,{direction:ke.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||S.VIDEO,{direction:ke.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?d||S.VIDEO:S.VIDEO,{direction:ke.SENDONLY,streams:[a]}),yield this.connect();else{let u=[];if(l&&(h[0].sender.track||u.push(0),yield h[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:S.AUDIO})),d){let m=o?3:1;yield h[m].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:S.VIDEO,videoType:o?S.AUXILIARY:S.BIG}),u.push(m),r&&(yield h[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:S.VIDEO,videoType:S.SMALL}),u.push(2))}yield this.setTransceiverDirection(ke.SENDONLY,u),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return A(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(ke.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ke.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 A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Hi()){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=de(Z({},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=de(Z({},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(ke.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 A(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:ve.PUBLISH_STATE_CHANGE,data:t,responseCommand:Ee.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ve.UNPUBLISH,commandDesc:"unpublish",responseCommand:Ee.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===H.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),Gi){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:ve.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Ee.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return A(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?S.AUXILIARY:S.MAIN} stream`),Yt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return A(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===S.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ke.INACTIVE&&(yield this.setTransceiverDirection(ke.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return A(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Hi()&&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===S.VIDEO&&e instanceof Nt&&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===Js||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=et(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===S.VIDEO)return!0;return!1}removeSender(e){let t=null;Hi()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&Fe(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return A(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?S.AUXILIARY:S.MAIN} stream`),Yt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return A(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===S.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(ke.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return A(this,null,function*(){if(!Ue)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,d=this._peerConnection.remoteDescription.sdp.split(`\r
76
+ `).map(l=>{if(l.match(new RegExp(`a=(${ke.INACTIVE}|${ke.RECVONLY}|${ke.SENDONLY})`))&&a++,t.includes(a)){if(e===ke.INACTIVE&&l.includes(`a=${ke.RECVONLY}`))return o=!0,`a=${e}`;if(e===ke.SENDONLY&&l.includes(`a=${ke.INACTIVE}`))return o=!0,`a=${ke.RECVONLY}`}return l}).join(`\r
77
+ `);o&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:d}))})}removeTrackBySender(e){return A(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===S.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===S.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===S.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return A(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(Yt()?r=e.kind===S.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?S.AUXILIARY:S.MAIN} stream`),e.kind===S.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===S.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return A(this,null,function*(){try{let r=yield this._peerConnection.createOffer(d_);Ue&&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===S.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:ve.PUBLISH_CHANGE,data:n,responseCommand:Ee.UPDATE_OFFER_RESULT,timeout:al,commandDesc:"update offer"}),{code:d,message:l}=a.data;d!==0&&this.checkPublishResultCode(d,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return A(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:o}){if(!Mn())return o?t===S.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e):void 0;let a,d=this._peerConnection.getSenders();if(Yt()){let l=0;t===S.VIDEO&&(r===S.SMALL?l=2:r===S.AUXILIARY?l=3:l=1),a=d[l]}else a=d.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),o}catch(h){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${h}`),o)return t===S.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,r){let o="AS";Ue&&(o="TIAS",t=t*1e3);let n=0,a=-1;return r===S.SMALL?n=1:r===S.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,d=>(a+=1,a===n?`${d}b=${o}:${t}\r
78
+ `:d)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return Ue&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
67
79
  c=IN $2\r
68
80
  b=${r}:${t}\r
69
- `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return p(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return p(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return p(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Cp);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Q.PUBLISH,responseCommand:H.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof at||this.localAuxVideoTrack instanceof at,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=Ce(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),At(o)}acceptAnswer(e){return p(this,null,function*(){var t,r,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),f=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let g=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:g})}f&&(c=yield this.setBandwidth({bandwidth:f,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:m}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||m.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this.setAnswer(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let 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(Q.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Fe($s.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Q.UNPUBLISH,responseCommand:H.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=Nt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(I.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ce(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===zr&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=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===hr?(this._log.error(we.NOT_SUPPORTED_H264ENCODE),new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})})):new y({code:S.UNKNOWN,message:P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:H.PUBLISH_RESULT,code:e,message:t}})})}};N([z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],$s.prototype,"publish",1),N([nt(521715,!1)],$s.prototype,"unpublish",1),N([Ke(it.prototype.afterConnect),ya(it.prototype.beforeConnect)],$s.prototype,"connect",1);var yu=$s,cn=yu;var dn=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,m,f;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===h.VIDEO){if(a.ssrc===r.video?(c=h.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=h.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=h.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!T(a.encoderImplementation)&&(c===h.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===h.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let D=2,_=this._prevEncoderImplementation;c===h.AUXILIARY&&(D=7,_=this._prevAuxEncoderImpl),E.emit("262",{userId:i.userId,streamType:D,prevImplementation:_,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?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(u=i.localMainVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(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"?tr(a)&&(this.totalBytesSent=a.bytesSent,J(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(!T(a.audioLevel)&&((f=i.localMainAudioTrack)!=null&&f.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let g=h.SMALL;a.trackIdentifier===i.getVideoTrackId(h.VIDEO)||a.ssrc===r.video?g=h.VIDEO:(a.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||a.ssrc===r.auxiliary)&&(g=h.AUXILIARY),e[g].frameWidth=a.frameWidth,e[g].frameHeight=a.frameHeight,e[g].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===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 p(this,null,function*(){var r,o,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(m=>{if(m.type==="inbound-rtp"){let f=(m.mediaType||m.kind)===h.AUDIO;if(f){if(m.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=m.packetsReceived,e.audio.bytesReceived=m.bytesReceived,e.audio.packetsLost=m.packetsLost,m.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=m.insertedSamplesForDeceleration),m.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=m.removedSamplesForAcceleration),m.totalSamplesDuration&&(e.audio.totalSamplesDuration=m.totalSamplesDuration),m.totalSamplesReceived&&(e.audio.totalSamplesReceived=m.totalSamplesReceived),m.concealedSamples&&(e.audio.concealedSamples=m.concealedSamples);let{remoteAudioTrack:g}=i;g.stat.packetsReceived=m.packetsReceived,g.stat.bytesReceived=m.bytesReceived,g.stat.packetsLost=m.packetsLost,e.audio.p2pDelay=g.stat.end2EndDelay,e.hasAudio=!0}else{if(ae&&m.bytesReceived===0)return;let g;m.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=m.packetsReceived,e.video.bytesReceived=m.bytesReceived,e.video.packetsLost=m.packetsLost,e.video.framesReceived=m.framesReceived,e.video.framesDecoded=m.framesDecoded,e.video.fpsDecoded=m.framesPerSecond,e.hasVideo=!0,g=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),m.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==m.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${m.decoderImplementation} HWDecoder: ${m.powerEfficientDecoder}`),E.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:m.decoderImplementation,codec:i.videoCodec,isHWCodec:m.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,m.decoderImplementation))),m.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=m.packetsReceived,e.auxiliary.bytesReceived=m.bytesReceived,e.auxiliary.packetsLost=m.packetsLost,e.auxiliary.framesReceived=m.framesReceived,e.auxiliary.framesDecoded=m.framesDecoded,e.auxiliary.fpsDecoded=m.framesPerSecond,g=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=g.stat.end2EndDelay,e.hasAuxiliary=!0),g&&(g.stat.packetsReceived=m.packetsReceived,g.stat.bytesReceived=m.bytesReceived,g.stat.packetsLost=m.packetsLost,g.stat.framesReceived=m.framesReceived,g.stat.framesDecoded=m.framesDecoded,m.jitterBufferDelay&&(g.stat.jitterBufferDelay=Math.floor(m.jitterBufferDelay/m.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=g.stat.end2EndDelay)}m.jitterBufferDelay&&(f?(e.audio.totalJitter=m.jitterBufferDelay,e.audio.totalJitterCount=m.jitterBufferEmittedCount):m.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=m.jitterBufferDelay,e.video.totalJitterCount=m.jitterBufferEmittedCount):m.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=m.jitterBufferDelay,e.auxiliary.totalJitterCount=m.jitterBufferEmittedCount))}else m.type==="candidate-pair"&&tr(m)&&(this.totalBytesReceived=m.bytesReceived,J(m.currentRoundTripTime)&&(e.rtt=Math.floor(m.currentRoundTripTime*1e3)));T(m.frameWidth)||((m.trackIdentifier===i.getMainStreamVideoTrackId()||m.ssrc===a.video)&&(e.video.frameWidth=m.frameWidth,e.video.frameHeight=m.frameHeight,i.remoteVideoTrack.stat.frameWidth=m.frameWidth,i.remoteVideoTrack.stat.frameHeight=m.frameHeight),(m.trackIdentifier===i.getAuxStreamVideoTrackId()||m.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=m.frameWidth,e.auxiliary.frameHeight=m.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=m.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=m.frameHeight)),!T(m.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&m.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=m.audioLevel||0,e.audio.totalAudioEnergy=m.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return p(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=x(),a=yield o.getStats(),c=x();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let l=[],u=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(m=>u.has(m.type)&&l.push(m)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(oi(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var f,g,D;if(!oi(i.senderStats)){let _={uint32_audio_level:i.senderStats.audio.audioLevel*Tt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(_.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Tt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let A=[];if(i.senderStats.video.bytesSent){let re={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};A.push(re)}if(i.senderStats.small.bytesSent){let re={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};A.push(re)}if(i.senderStats.auxiliary.bytesSent){let re={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};A.push(re)}let O={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:_,msg_video_status:A,msg_network_status:O}}let r=(f=Re())==null?void 0:f.playoutStats;r&&(e.msg_device_info.uint32_audio_play_cost=r.totalFramesDuration);let{statInterval:o}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(_=>{let A={msg_user_info:{str_identifier:_.userId,uint64_tinyid:_.tinyId},msg_network_status:{uint32_rtt:_.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(_.hasAudio){let O={uint32_audio_p2p_delay:_.audio.p2pDelay,uint32_audio_cache_ms:_.audio.totalJitter,uint32_audio_cache_ms_count:_.audio.totalJitterCount,uint32_audio_codec_bitrate:_.audio.bytesReceived,uint32_audio_total_bitrate:_.audio.bytesReceived,uint32_audio_level:_.audio.audioLevel*1e8,uint32_audio_energy:_.audio.totalAudioEnergy*1e6,uint32_audio_receive:_.audio.packetsReceived,uint32_audio_origin_lost:_.audio.packetsLost};A.msg_audio_status=O}if(_.hasVideo){let O=t.get(`${_.userId}_${Bc}`),re=O?O.duration:0,Z={uint32_video_stream_type:_.isSmallSubscribed?3:2,uint32_video_receive_fps:_.video.framesReceived,uint32_video_width:_.video.frameWidth,uint32_video_height:_.video.frameHeight,uint32_video_codec_bitrate:_.video.bytesReceived,uint32_video_receive:_.video.packetsReceived,uint32_video_origin_lost:_.video.packetsLost,uint32_video_block_time:re,uint32_video_dec_fps:_.video.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.video.totalJitter,uint32_video_cache_ms_count:_.video.totalJitterCount,uint32_video_p2p_delay:_.video.p2pDelay};A.msg_video_status.push(Z)}if(_.hasAuxiliary){let O=t.get(`${_.userId}_${Fc}`),re=O?O.duration:0,Z={uint32_video_stream_type:7,uint32_video_receive_fps:_.auxiliary.framesReceived,uint32_video_width:_.auxiliary.frameWidth,uint32_video_height:_.auxiliary.frameHeight,uint32_video_codec_bitrate:_.auxiliary.bytesReceived,uint32_video_receive:_.auxiliary.packetsReceived+_.auxiliary.packetsLost,uint32_video_origin_lost:_.auxiliary.packetsLost,uint32_video_block_time:re,uint32_video_dec_fps:_.auxiliary.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.auxiliary.totalJitter,uint32_video_cache_ms_count:_.auxiliary.totalJitterCount,uint32_video_p2p_delay:_.auxiliary.p2pDelay};A.msg_video_status.push(Z)}e.msg_down_stream_info.push(A)});let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let _=n.msg_up_stream_info.msg_audio_status,A=e.msg_up_stream_info.msg_audio_status;if(_.uint32_audio_codec_bitrate===0)A.uint32_audio_codec_bitrate=0;else{let O=this.getDifferenceValue(_.uint32_audio_codec_bitrate,A.uint32_audio_codec_bitrate);A.uint32_audio_codec_bitrate=Math.round(O*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=A.uint32_audio_codec_bitrate}(g=n.msg_device_info)!=null&&g.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/o):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(_=>{let A=c.find(U=>U.uint32_video_stream_type===_.uint32_video_stream_type);if(!A||A.uint32_video_codec_bitrate===0){_.uint32_video_codec_bitrate=0,_.uint32_video_enc_fps=0,_.uint32_video_codec_fps=0;return}let O=0,re=0,Z=0;A&&_.uint32_video_codec_bitrate>=A.uint32_video_codec_bitrate&&(O=A.uint32_video_codec_bitrate,re=A.uint32_video_enc_fps,Z=A.uint32_video_codec_fps);let Y=this.getDifferenceValue(O,_.uint32_video_codec_bitrate);_.uint32_video_codec_bitrate=Math.round(Y*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_video_codec_bitrate,_.uint32_video_enc_fps=Math.round(this.getDifferenceValue(re,_.uint32_video_enc_fps)/o),_.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Z,_.uint32_video_codec_fps)/o),A.uint32_video_width===0&&A.uint32_video_height===0&&A.uint32_video_codec_fps===0&&(_.uint32_video_codec_fps=_.uint32_video_enc_fps),T(A.uint32_key_frame_count)||(_.uint32_key_frame_count=Math.round(this.getDifferenceValue(A.uint32_key_frame_count,_.uint32_key_frame_count))),T(A.uint32_nack_count)||(_.uint32_nack_count=Math.round(this.getDifferenceValue(A.uint32_nack_count,_.uint32_nack_count))),T(A.uint32_pli_count)||(_.uint32_pli_count=Math.round(this.getDifferenceValue(A.uint32_pli_count,_.uint32_pli_count))),T(A.uint32_video_arq_packets)||(_.uint32_video_arq_packets=Math.round(this.getDifferenceValue(A.uint32_video_arq_packets,_.uint32_video_arq_packets))),T(A.uint32_encode_cost)||(_.uint32_encode_cost=Math.round(this.getDifferenceValue(A.uint32_encode_cost,_.uint32_encode_cost)/o)),T(A.uint32_send_packet_cost)||(_.uint32_send_packet_cost=Math.round(this.getDifferenceValue(A.uint32_send_packet_cost,_.uint32_send_packet_cost)/o))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(_=>u.find(A=>A.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid));let m=e.msg_down_stream_info;return m.forEach(_=>{let A=u.find(O=>O.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid);if(!oi(_.msg_audio_status)&&!oi(A.msg_audio_status)){let O=_.msg_audio_status,re=A.msg_audio_status,Z=this.getDifferenceValue(re.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms_count);delete O.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(re.uint32_audio_cache_ms,O.uint32_audio_cache_ms)/Z)||0;let Y=this.room.remotePublishedUserMap.get(_.msg_user_info.str_identifier);Y&&(Y.remoteAudioTrack.stat.jitterBufferDelay=O.uint32_audio_cache_ms),O.uint32_audio_origin_lost=this.getDifferenceValue(re.uint32_audio_origin_lost,O.uint32_audio_origin_lost),O.uint32_audio_receive=this.getDifferenceValue(re.uint32_audio_receive,O.uint32_audio_receive),O.uint32_audio_receive+=O.uint32_audio_origin_lost;let U=this.getDifferenceValue(re.uint32_audio_codec_bitrate,O.uint32_audio_codec_bitrate);O.uint32_audio_codec_bitrate=Math.round(U*8/o),O.uint32_audio_total_bitrate=Math.round(U*8/o)}else _.msg_audio_status={};if(_.msg_video_status&&A.msg_video_status){let O=A.msg_video_status;_.msg_video_status=_.msg_video_status.filter(Z=>O.find(Y=>Y.uint32_video_stream_type===Z.uint32_video_stream_type)),_.msg_video_status.forEach(Z=>{let Y=O.find(af=>af.uint32_video_stream_type===Z.uint32_video_stream_type),U=Y.uint32_video_receive,Kp=Y.uint32_video_origin_lost,ef=Y.uint32_video_codec_bitrate,tf=Y.uint32_video_receive_fps,rf=Y.uint32_video_dec_fps;Z.uint32_video_origin_lost=this.getDifferenceValue(Kp,Z.uint32_video_origin_lost),Z.uint32_video_receive=this.getDifferenceValue(U,Z.uint32_video_receive)+Z.uint32_video_origin_lost;let sf=this.getDifferenceValue(ef,Z.uint32_video_codec_bitrate);Z.uint32_video_codec_bitrate=Math.round(sf*8/o);let of=this.getDifferenceValue(tf,Z.uint32_video_receive_fps);Z.uint32_video_receive_fps=Math.round(of/o),Z.uint32_video_dec_fps=Math.round(this.getDifferenceValue(rf,Z.uint32_video_dec_fps)/o);let nf=this.getDifferenceValue(Y.uint32_video_cache_ms_count,Z.uint32_video_cache_ms_count);delete Z.uint32_video_cache_ms_count,Z.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Y.uint32_video_cache_ms,Z.uint32_video_cache_ms)/nf)||0})}}),(D=n.msg_device_info)!=null&&D.uint32_audio_play_cost?e.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_play_cost,e.msg_device_info.uint32_audio_play_cost)/o):delete e.msg_device_info.uint32_audio_play_cost,a&&i.receiverStats.forEach(_=>{if(_.audio.concealedSamples&&_.audio.totalSamplesReceived){let A=a.receiverStats.find(O=>O.userId===_.userId);if(A&&A.audio.concealedSamples&&A.audio.totalSamplesReceived){let O=_.audio.concealedSamples-A.audio.concealedSamples,re=_.audio.totalSamplesReceived-A.audio.totalSamplesReceived,Z=Math.floor(O/re*1e3*o);if(Z>o*1e3/5){let Y=m.find(U=>U.msg_user_info.str_identifier===_.userId);Y&&(Y.msg_audio_status.uint32_audio_block_time=Z)}}}}),e}getStatsReport(r){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var bp=Be(Qe());function Rp(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),m=Math.round(t.responseStart-t.requestStart),f=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=w(v({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:c,tcp:u,tls:l,request:m,response:f});break}}catch(e){}return i}function yp(s){return new Promise(i=>p(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=Rp(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var QT=700,Gr=class Gr extends bp.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=C.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(H.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(be.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===fe.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:m});continue}let f=0,g=this._downlinkPrevStatMap.get(c),D=u-g.totalPacketsLost,_=m-g.totalPacketsReceived;D<=0||_<0?f=0:f=Math.round(D/(D+_)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:f,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!vr())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"&&J(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===fe.DISCONNECTED||e.connectionState===fe.FAILED||e.connectionState===fe.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=oe.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];E.emit(I.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=w(v({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Gr.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Gr.lastPingTime>t.interval*1e3){Gr.lastPingTime=Date.now();let a=t.domain.map(c=>yp(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>QT),this.pingResults.timestamp=o,this.pingResults.data=c,c.forEach(l=>{b.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(oe.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}};d(Gr,"EVENT_NETWORK_QUALITY","0"),d(Gr,"lastPingTime",0);var Hs=Gr;function YT({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return Qi(t)?t.catch(r=>C.error(`${s.name}() error observed ${r}`)):t}catch(t){C.error(`${s.name}() error observed ${t}`)}}}var fc=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=C.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ne(this[e])&&(this[e]=YT({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:ke,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,Eo().then(i=>{this._basicInfo.string_os_version=bi(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),E.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(I.JOIN_START,this.handleJoinStart).addEvent(I.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(I.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(I.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(I.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(I.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(I.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(I.JOIN_FAILED,this.handleJoinFailed).addEvent(I.LEAVE_START,this.handleLeaveStart).addEvent(I.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(I.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(I.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(I.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(I.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(I.PUBLISH_START,this.handlePublishStart).addEvent(I.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(I.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(I.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(I.PLAY_TRACK_START,this.handlePlayStart).addEvent(I.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(I.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(I.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(I.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(I.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(I.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(I.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>E.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),oe.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:o,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof y?Number(e.getExtraCode()||e.getCode()):S.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:w(v({},ZT),{msg_user_info:new ln({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 ln({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${o}_${t}`,m=this._remoteStreamStatMap.get(u);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,b.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,u,m;o&&(l=o,u=1),n&&(c=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:m,videoDelayCount:u})}}))}handleHeartbeatStats(i){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/Tt*100)>0&&(this._localStreamStat.totalAudioLevel+=o/Tt,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,l=n.str_identifier,u=this._room.remotePublishedUserMap.get(l);if(c.forEach(m=>{let f=m.uint32_video_stream_type===2,g=m.uint32_video_stream_type===7,D=`${l}_${f?"main":"auxiliary"}`,_=this._remoteStreamStatMap.get(D);if(_&&(f&&(u!=null&&u.remoteVideoTrack.isSubscribed)||g&&(u!=null&&u.remoteAuxiliaryTrack))){_.totalVideoFPS+=m.uint32_video_receive_fps,_.totalVideoBitrate+=m.uint32_video_codec_bitrate,_.videoCount++,_.statsToReport.uint32_video_width===0&&(_.statsToReport.uint32_video_width=m.uint32_video_width),_.statsToReport.uint32_video_height===0&&(_.statsToReport.uint32_video_height=m.uint32_video_height);let A=f?u.remoteVideoTrack:u.remoteAuxiliaryTrack;A.stat.jitterBufferDelay&&(_.videoJitterBufferDelay=A.stat.jitterBufferDelay),A.stat.framesReceived&&(_.statsToReport.uint32_video_consume_render_rate=Math.floor(A.stat.framesDecoded/A.stat.framesReceived*Wi(10,6)))}}),!Kr(a)){let m=`${l}_main`,f=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&f&&u!=null&&u.remoteAudioTrack.isSubscribed&&(f.totalAudioBitrate+=a.uint32_audio_codec_bitrate,f.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(f.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/Tt*100)>0&&(f.totalAudioLevel+=a.uint32_audio_level/Tt,f.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof y?e.getExtraCode()||e.getCode():S.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&qi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Xi)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&mr)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:m,audioDelayCount:f,videoDelayCount:g,totalAudioDelay:D,totalVideoDelay:_}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/m),f&&D&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(D/f),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),g&&_&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(_/g))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Wr));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Wr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Wr)}),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>Wr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Wr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Wr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Wr)}getReportData(){this._basicInfo.uint32_networkType=gr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ln({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:es(this._signalInfo.relayIp),uint32_client_ip:es(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Wi(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:es(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return oo(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return p(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield Yc(i),r=t instanceof ArrayBuffer,o=`${Ei(e,Ji.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(b),this.uploadKVStat(br)];n||a.push(Ai({url:o,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=w(v({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield Yc(e),r=`${Ei(+this._room.sdkAppId,Ji.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||Ai({url:r,body:t})})}};N([ht({settings:{timeout:500,retries:3}})],fc.prototype,"upload",1);var Wr=5e3,ZT={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},ln=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},vp=fc;var bu=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=x())}stop(){this._endTime===0&&(this._endTime=x())}getDuration(){return this._endTime===0?x()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},_c=bu;var vu=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(I.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(I.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(I.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,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)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new _c,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()}},Np=vu;var Nu=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new Map);d(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(I.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(I.PLAY_TRACK_START,this.onPlayTrackStart).set(I.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(I.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(I.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==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(I.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new _c;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>bn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return p(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=x();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=x();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==h.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<bn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=x(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},Dp=Nu;var kp=Be(Qe(),1);var KT=[1,0,0,0,1,1,0,1],gc=class extends tt{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof Oe)try{this.setTexBuffer(KT)}catch(t){i.destroy(new y({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,r,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,r,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Du=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Tc=class extends tt{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new 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 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((r,o)=>(!o||!o.node.requestFrame(e))&&r,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:l,name:a},v({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof Oe))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var Ec=class{constructor(i,e,t,r=4/3){this.vbMode=i;this.faceDetector=e;this.logger=t;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(this,"restTime",1e3);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetector),this.originalAspect=r||4/3}addEvent(i,e,t){let o=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];o&&(e?b.addSuccessEvent({key:o.key}):b.addFailedEvent({key:o.key,error:o.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetector||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20;try{let o=this.faceDetector.detectForVideo(i,Date.now());if(o.detections.length<=0){this.recoverOriginal(t,r);return}let n=o.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,u=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,u):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,u)}catch(o){this.logger.error(o)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let o,n;return i>e/2?(o=e-t-r,n=t-o):(o=t,n=0),{min:o,offset:n}}calculateTargetPosition(i,e,t,r,o,n,a=.4){let c=i+t/2,l=e+r/2,u,m,{min:f,offset:g}=this.calculateBoundary(c,o,i,t),{min:D,offset:_}=this.calculateBoundary(l,n,e,r);return u=2*f+t,m=2*D+r,u/m>this.originalAspect?(u=m*this.originalAspect,g=c-u/2):(m=u/this.originalAspect,_=l-m/2),t/o>a&&(g=0,_=0,u=o,m=n),g=Math.max(0,Math.min(g,o-u)),_=Math.max(0,Math.min(_,n-m)),{sx:g,sy:_,cropWidth:u,cropHeight:m,timestamp:Date.now()}}processFacePositionCrop(i,e){if(!this.animationState.current||!this.animationState.target){this.animationState.current=v({},i),this.animationState.target=v({},i);return}let t=this.positionDistance(this.animationState.target,i),r=this.positionDistance(this.animationState.current,i),o=this.animationState.current.cropWidth/e;t>this.animationState.debounceThreshold*o&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold*o&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=v({},i),this.animationState.target=v({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let o=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=o,this.totalOffsetY+=o,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),J(this.animationState.current.scaleOffsetX)&&J(this.animationState.target.scaleOffsetX)&&J(this.animationState.current.scaleOffsetY)&&J(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(Wi(i.sx-e.sx,2)+Wi(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,o,n,a=.55){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,o,n,i,e,a);this.processFacePositionCrop(c,i),o/c.cropWidth>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,o,n){var c,l,u,m,f,g,D,_,A,O,re,Z;let a={sx:t+o/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(m=(u=this.animationState.current)==null?void 0:u.scaleOffsetX)!=null?m:0,scaleOffsetY:(g=(f=this.animationState.current)==null?void 0:f.scaleOffsetY)!=null?g:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(_=(D=this.animationState.target)==null?void 0:D.scaleRatio)!=null?_:1,scaleOffsetX:(O=(A=this.animationState.target)==null?void 0:A.scaleOffsetX)!=null?O:0,scaleOffsetY:(Z=(re=this.animationState.target)==null?void 0:re.scaleOffsetY)!=null?Z:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(o*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var eE=`#version 300 es
81
+ `),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 A(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return A(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 A(this,null,function*(){try{let e=yield this._peerConnection.createOffer(d_);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:ve.PUBLISH,responseCommand:Ee.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof jt||this.localAuxVideoTrack instanceof jt,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=et(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),li(o)}acceptAnswer(e){return A(this,null,function*(){var t,r,o,n,a;try{let d;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let u=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),m=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(u){let p=this._isPublishingAux?S.AUXILIARY:S.BIG;d=yield this.setBandwidth({bandwidth:u,type:S.VIDEO,sdp:d,videoType:p})}m&&(d=yield this.setBandwidth({bandwidth:m,type:S.AUDIO,sdp:d}))}if(d=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:u}=this._room;d=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||u.bitrate,type:S.VIDEO,videoType:S.SMALL,sdp:d})}let h={type:e.type,sdp:d};yield this.setAnswer(h),this._log.debug(`accepted answer: ${d}`)}catch(d){throw this._log.error(`failed to accept remote answer ${d}`),d}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(ve.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return A(this,null,function*(){if(!(Ct(Fo.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:ve.UNPUBLISH,responseCommand:Ee.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=pi(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)&&x.emit(B.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{et(e).media.forEach((r,o)=>{if(r.type===S.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Js&&r.ssrcGroups){r.ssrcGroups.forEach((a,d)=>{let l=Number(a.ssrcs.split(" ")[0]);d===0?this.ssrc.video=l:d===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=S.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===S.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===S.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===S.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===S.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===cs?(this._log.error(Tt.NOT_SUPPORTED_H264ENCODE),new X({code:H.NOT_SUPPORTED_H264,message:pe({key:me.NOT_SUPPORTED_H264ENCODE})})):new X({code:H.UNKNOWN,message:pe({key:me.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ee.PUBLISH_RESULT,code:e,message:t}})})}};J([be(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Fo.prototype,"publish",1),J([zt(521715,!1)],Fo.prototype,"unpublish",1),J([Ut($t.prototype.afterConnect),xd($t.prototype.beforeConnect)],Fo.prototype,"connect",1);var Yh=Fo,fa=Yh;var _a=class{constructor(i,e){this.room=i;c(this,"_log");c(this,"_prevReportTime",0);c(this,"_prevReport",{});c(this,"_prevStats",null);c(this,"_prevEncoderImplementation","");c(this,"_prevAuxEncoderImpl","");c(this,"_prevQualityLimitationReason","");c(this,"_prevAuxQualityLimitationReason","");c(this,"_prevDecoderImplementationMap",new Map);c(this,"totalBytesSent",0);c(this,"totalBytesReceived",0);c(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return A(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var h,u,m;let d,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===S.VIDEO){if(a.ssrc===r.video?(d=S.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?d=S.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,d=S.AUXILIARY),!d)return;if(e[d].bytesSent=a.bytesSent,e[d].packetsSent=a.packetsSent,e[d].framesEncoded=a.framesEncoded,M(a.keyFramesEncoded)||(e[d].keyFramesEncoded=a.keyFramesEncoded),M(a.nackCount)||(e[d].nackCount=a.nackCount),M(a.pliCount)||(e[d].pliCount=a.pliCount),M(a.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=a.retransmittedPacketsSent),M(a.totalEncodeTime)||(e[d].totalEncodeTime=a.totalEncodeTime),M(a.totalPacketSendDelay)||(e[d].totalPacketSendDelay=a.totalPacketSendDelay),!M(a.encoderImplementation)&&(d===S.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||d===S.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let g=2,f=this._prevEncoderImplementation;d===S.AUXILIARY&&(g=7,f=this._prevAuxEncoderImpl),x.emit("262",{userId:i.userId,streamType:g,prevImplementation:f,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[d===S.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${d===S.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!M(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),x.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(h=i.localMainVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!M(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),x.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(u=i.localAuxVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?Xr(a)&&(this.totalBytesSent=a.bytesSent,De(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===S.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===S.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(S.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(S.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!M(a.audioLevel)&&((m=i.localMainAudioTrack)!=null&&m.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!M(a.frameWidth)){let p=S.SMALL;a.trackIdentifier===i.getVideoTrackId(S.VIDEO)||a.ssrc===r.video?p=S.VIDEO:(a.trackIdentifier===i.getVideoTrackId(S.AUXILIARY)||a.ssrc===r.auxiliary)&&(p=S.AUXILIARY),e[p].frameWidth=a.frameWidth,e[p].frameHeight=a.frameHeight,e[p].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===S.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===S.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===S.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 A(this,null,function*(){var r,o,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:d,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(u=>{if(u.type==="inbound-rtp"){let m=(u.mediaType||u.kind)===S.AUDIO;if(m){if(u.ssrc!==a.audio||!d.hasAudio)return;e.audio.packetsReceived=u.packetsReceived,e.audio.bytesReceived=u.bytesReceived,e.audio.packetsLost=u.packetsLost,u.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=u.insertedSamplesForDeceleration),u.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=u.removedSamplesForAcceleration),u.totalSamplesDuration&&(e.audio.totalSamplesDuration=u.totalSamplesDuration),u.totalSamplesReceived&&(e.audio.totalSamplesReceived=u.totalSamplesReceived),u.concealedSamples&&(e.audio.concealedSamples=u.concealedSamples);let{remoteAudioTrack:p}=i;p.stat.packetsReceived=u.packetsReceived,p.stat.bytesReceived=u.bytesReceived,p.stat.packetsLost=u.packetsLost,e.audio.p2pDelay=p.stat.end2EndDelay,e.hasAudio=!0}else{if(Ue&&u.bytesReceived===0)return;let p;u.ssrc===a.video&&d.hasVideo&&(e.video.packetsReceived=u.packetsReceived,e.video.bytesReceived=u.bytesReceived,e.video.packetsLost=u.packetsLost,e.video.framesReceived=u.framesReceived,e.video.framesDecoded=u.framesDecoded,e.video.fpsDecoded=u.framesPerSecond,e.hasVideo=!0,p=i.remoteVideoTrack,d.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),u.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==u.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${u.decoderImplementation} HWDecoder: ${u.powerEfficientDecoder}`),x.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:u.decoderImplementation,codec:i.videoCodec,isHWCodec:u.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,u.decoderImplementation))),u.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.packetsReceived=u.packetsReceived,e.auxiliary.bytesReceived=u.bytesReceived,e.auxiliary.packetsLost=u.packetsLost,e.auxiliary.framesReceived=u.framesReceived,e.auxiliary.framesDecoded=u.framesDecoded,e.auxiliary.fpsDecoded=u.framesPerSecond,p=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),p&&(p.stat.packetsReceived=u.packetsReceived,p.stat.bytesReceived=u.bytesReceived,p.stat.packetsLost=u.packetsLost,p.stat.framesReceived=u.framesReceived,p.stat.framesDecoded=u.framesDecoded,u.jitterBufferDelay&&(p.stat.jitterBufferDelay=Math.floor(u.jitterBufferDelay/u.jitterBufferEmittedCount*1e3)))}u.jitterBufferDelay&&(m?(e.audio.totalJitter=u.jitterBufferDelay,e.audio.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.video&&d.hasVideo?(e.video.totalJitter=u.jitterBufferDelay,e.video.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.totalJitter=u.jitterBufferDelay,e.auxiliary.totalJitterCount=u.jitterBufferEmittedCount))}else u.type==="candidate-pair"&&Xr(u)&&(this.totalBytesReceived=u.bytesReceived,De(u.currentRoundTripTime)&&(e.rtt=Math.floor(u.currentRoundTripTime*1e3)));M(u.frameWidth)||((u.trackIdentifier===i.getMainStreamVideoTrackId()||u.ssrc===a.video)&&(e.video.frameWidth=u.frameWidth,e.video.frameHeight=u.frameHeight,i.remoteVideoTrack.stat.frameWidth=u.frameWidth,i.remoteVideoTrack.stat.frameHeight=u.frameHeight),(u.trackIdentifier===i.getAuxStreamVideoTrackId()||u.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=u.frameWidth,e.auxiliary.frameHeight=u.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=u.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=u.frameHeight)),!M(u.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&u.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=u.audioLevel||0,e.audio.totalAudioEnergy=u.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),M((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),M((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return A(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=le(),a=yield o.getStats(),d=le();d-n>2e3&&this._log.warn(`getStats cost ${d-n}ms`);let l=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(u=>h.has(u.type)&&l.push(u)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(qi(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var u;if(!qi(i.senderStats)){let m={uint32_audio_level:i.senderStats.audio.audioLevel*ai,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(m.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*ai),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let p=[];if(i.senderStats.video.bytesSent){let f={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};p.push(f)}if(i.senderStats.small.bytesSent){let f={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};p.push(f)}if(i.senderStats.auxiliary.bytesSent){let f={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};p.push(f)}let g={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:m,msg_video_status:p,msg_network_status:g}}let{statInterval:r}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(m=>{let p={msg_user_info:{str_identifier:m.userId,uint64_tinyid:m.tinyId},msg_network_status:{uint32_rtt:m.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(m.hasAudio){let g={uint32_audio_p2p_delay:m.audio.p2pDelay,uint32_audio_cache_ms:m.audio.totalJitter,uint32_audio_cache_ms_count:m.audio.totalJitterCount,uint32_audio_codec_bitrate:m.audio.bytesReceived,uint32_audio_total_bitrate:m.audio.bytesReceived,uint32_audio_level:m.audio.audioLevel*1e8,uint32_audio_energy:m.audio.totalAudioEnergy*1e6,uint32_audio_receive:m.audio.packetsReceived,uint32_audio_origin_lost:m.audio.packetsLost};p.msg_audio_status=g}if(m.hasVideo){let g=t.get(`${m.userId}_${sl}`),f=g?g.duration:0,T={uint32_video_stream_type:m.isSmallSubscribed?3:2,uint32_video_receive_fps:m.video.framesReceived,uint32_video_width:m.video.frameWidth,uint32_video_height:m.video.frameHeight,uint32_video_codec_bitrate:m.video.bytesReceived,uint32_video_receive:m.video.packetsReceived,uint32_video_origin_lost:m.video.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:m.video.framesDecoded,uint32_video_codec_fps:m.video.fpsRender,uint32_video_cache_ms:m.video.totalJitter,uint32_video_cache_ms_count:m.video.totalJitterCount};p.msg_video_status.push(T)}if(m.hasAuxiliary){let g=t.get(`${m.userId}_${ol}`),f=g?g.duration:0,T={uint32_video_stream_type:7,uint32_video_receive_fps:m.auxiliary.framesReceived,uint32_video_width:m.auxiliary.frameWidth,uint32_video_height:m.auxiliary.frameHeight,uint32_video_codec_bitrate:m.auxiliary.bytesReceived,uint32_video_receive:m.auxiliary.packetsReceived+m.auxiliary.packetsLost,uint32_video_origin_lost:m.auxiliary.packetsLost,uint32_video_block_time:f,uint32_video_dec_fps:m.auxiliary.framesDecoded,uint32_video_codec_fps:m.video.fpsRender,uint32_video_cache_ms:m.auxiliary.totalJitter,uint32_video_cache_ms_count:m.auxiliary.totalJitterCount};p.msg_video_status.push(T)}e.msg_down_stream_info.push(p)});let o=this._prevReport,n=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let m=o.msg_up_stream_info.msg_audio_status,p=e.msg_up_stream_info.msg_audio_status;if(m.uint32_audio_codec_bitrate===0)p.uint32_audio_codec_bitrate=0;else{let g=this.getDifferenceValue(m.uint32_audio_codec_bitrate,p.uint32_audio_codec_bitrate);p.uint32_audio_codec_bitrate=Math.round(g*8/r),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=p.uint32_audio_codec_bitrate}(u=o.msg_device_info)!=null&&u.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/r):delete e.msg_device_info.uint32_audio_capture_cost}let a=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(m=>{let p=a.find(v=>v.uint32_video_stream_type===m.uint32_video_stream_type);if(!p||p.uint32_video_codec_bitrate===0){m.uint32_video_codec_bitrate=0,m.uint32_video_enc_fps=0,m.uint32_video_codec_fps=0;return}let g=0,f=0,T=0;p&&m.uint32_video_codec_bitrate>=p.uint32_video_codec_bitrate&&(g=p.uint32_video_codec_bitrate,f=p.uint32_video_enc_fps,T=p.uint32_video_codec_fps);let I=this.getDifferenceValue(g,m.uint32_video_codec_bitrate);m.uint32_video_codec_bitrate=Math.round(I*8/r),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_video_codec_bitrate,m.uint32_video_enc_fps=Math.round(this.getDifferenceValue(f,m.uint32_video_enc_fps)/r),m.uint32_video_codec_fps=Math.round(this.getDifferenceValue(T,m.uint32_video_codec_fps)/r),p.uint32_video_width===0&&p.uint32_video_height===0&&p.uint32_video_codec_fps===0&&(m.uint32_video_codec_fps=m.uint32_video_enc_fps),M(p.uint32_key_frame_count)||(m.uint32_key_frame_count=Math.round(this.getDifferenceValue(p.uint32_key_frame_count,m.uint32_key_frame_count))),M(p.uint32_nack_count)||(m.uint32_nack_count=Math.round(this.getDifferenceValue(p.uint32_nack_count,m.uint32_nack_count))),M(p.uint32_pli_count)||(m.uint32_pli_count=Math.round(this.getDifferenceValue(p.uint32_pli_count,m.uint32_pli_count))),M(p.uint32_video_arq_packets)||(m.uint32_video_arq_packets=Math.round(this.getDifferenceValue(p.uint32_video_arq_packets,m.uint32_video_arq_packets))),M(p.uint32_encode_cost)||(m.uint32_encode_cost=Math.round(this.getDifferenceValue(p.uint32_encode_cost,m.uint32_encode_cost)/r)),M(p.uint32_send_packet_cost)||(m.uint32_send_packet_cost=Math.round(this.getDifferenceValue(p.uint32_send_packet_cost,m.uint32_send_packet_cost)/r))});let l=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(m=>l.find(p=>p.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;return h.forEach(m=>{let p=l.find(g=>g.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid);if(!qi(m.msg_audio_status)&&!qi(p.msg_audio_status)){let g=m.msg_audio_status,f=p.msg_audio_status,T=this.getDifferenceValue(f.uint32_audio_cache_ms_count,g.uint32_audio_cache_ms_count);delete g.uint32_audio_cache_ms_count,g.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(f.uint32_audio_cache_ms,g.uint32_audio_cache_ms)/T)||0;let I=this.room.remotePublishedUserMap.get(m.msg_user_info.str_identifier);I&&(I.remoteAudioTrack.stat.jitterBufferDelay=g.uint32_audio_cache_ms),g.uint32_audio_origin_lost=this.getDifferenceValue(f.uint32_audio_origin_lost,g.uint32_audio_origin_lost),g.uint32_audio_receive=this.getDifferenceValue(f.uint32_audio_receive,g.uint32_audio_receive),g.uint32_audio_receive+=g.uint32_audio_origin_lost;let v=this.getDifferenceValue(f.uint32_audio_codec_bitrate,g.uint32_audio_codec_bitrate);g.uint32_audio_codec_bitrate=Math.round(v*8/r),g.uint32_audio_total_bitrate=Math.round(v*8/r)}else m.msg_audio_status={};if(m.msg_video_status&&p.msg_video_status){let g=p.msg_video_status;m.msg_video_status=m.msg_video_status.filter(T=>g.find(I=>I.uint32_video_stream_type===T.uint32_video_stream_type)),m.msg_video_status.forEach(T=>{let I=g.find(y=>y.uint32_video_stream_type===T.uint32_video_stream_type),v=I.uint32_video_receive,b=I.uint32_video_origin_lost,w=I.uint32_video_codec_bitrate,N=I.uint32_video_receive_fps,q=I.uint32_video_dec_fps;T.uint32_video_origin_lost=this.getDifferenceValue(b,T.uint32_video_origin_lost),T.uint32_video_receive=this.getDifferenceValue(v,T.uint32_video_receive)+T.uint32_video_origin_lost;let $=this.getDifferenceValue(w,T.uint32_video_codec_bitrate);T.uint32_video_codec_bitrate=Math.round($*8/r);let te=this.getDifferenceValue(N,T.uint32_video_receive_fps);T.uint32_video_receive_fps=Math.round(te/r),T.uint32_video_dec_fps=Math.round(this.getDifferenceValue(q,T.uint32_video_dec_fps)/r);let se=this.getDifferenceValue(I.uint32_video_cache_ms_count,T.uint32_video_cache_ms_count);delete T.uint32_video_cache_ms_count,T.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(I.uint32_video_cache_ms,T.uint32_video_cache_ms)/se)||0})}}),n&&i.receiverStats.forEach(m=>{if(m.audio.concealedSamples&&m.audio.totalSamplesReceived){let p=n.receiverStats.find(g=>g.userId===m.userId);if(p&&p.audio.concealedSamples&&p.audio.totalSamplesReceived){let g=m.audio.concealedSamples-p.audio.concealedSamples,f=m.audio.totalSamplesReceived-p.audio.totalSamplesReceived,T=Math.floor(g/f*1e3*r);if(T>r*1e3/5){let I=h.find(v=>v.msg_user_info.str_identifier===m.userId);I&&(I.msg_audio_status.uint32_audio_block_time=T)}}}}),e}getStatsReport(r){return A(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var u_=gt(Mt());function c_(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,d=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),h=Math.round(t.secureConnectionStart-t.connectStart),u=Math.round(t.responseStart-t.requestStart),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=de(Z({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:d,tcp:h,tls:l,request:u,response:m});break}}catch(e){}return i}function l_(s){return new Promise(i=>A(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=c_(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var wS=700,Fs=class Fs extends u_.default{constructor({signalChannel:e,room:t}){super();c(this,"_room");c(this,"_signalChannel");c(this,"_log");c(this,"uplinkRTT",0);c(this,"uplinkLoss",0);c(this,"downlinkRTT",0);c(this,"downlinkLoss",0);c(this,"pingResults",{});c(this,"_downlinkPrevStatMap",new Map);c(this,"_downlinkLossAndRTTMap",new Map);c(this,"_interval",-1);c(this,"_uplinkNetworkQuality",0);c(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=z.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(Ee.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(rt.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var d,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(d=this._room)==null?void 0:d.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return A(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)===Je.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let d=t[a].getPeerConnection();if(!d)return;let{rtt:l,totalPacketsLost:h,totalPacketsReceived:u}=yield this.getStat(d);if(!this._downlinkPrevStatMap.has(d)){this._downlinkPrevStatMap.set(d,{totalPacketsLost:h,totalPacketsReceived:u});continue}let m=0,p=this._downlinkPrevStatMap.get(d),g=h-p.totalPacketsLost,f=u-p.totalPacketsReceived;g<=0||f<0?m=0:m=Math.round(g/(g+f)*100),this._downlinkPrevStatMap.set(d,{totalPacketsLost:h,totalPacketsReceived:u}),this._downlinkLossAndRTTMap.set(d,{rtt:l,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return A(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Rs())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(d=>{d.type==="candidate-pair"&&De(d.currentRoundTripTime)&&(t.rtt=Math.round(d.currentRoundTripTime*1e3)),d.type==="inbound-rtp"&&(d.mediaType===S.AUDIO||d.mediaType===S.VIDEO)&&(t.totalPacketsLost+=d.packetsLost,t.totalPacketsReceived+=d.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===Je.DISCONNECTED||e.connectionState===Je.FAILED||e.connectionState===Je.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=Le.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];x.emit(B.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=de(Z({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Fs.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Fs.lastPingTime>t.interval*1e3){Fs.lastPingTime=Date.now();let a=t.domain.map(d=>l_(d).then(l=>({domain:d,cost:l.totalCost})));Promise.all(a).then(d=>{this.pingResults.isPoorNetwork=d.some(l=>l.cost>wS),this.pingResults.timestamp=o,this.pingResults.data=d,d.forEach(l=>{Q.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(d)}`)}).catch(d=>{this._log.warn(`Error during pinging domains: ${d}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(Le.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let d=this._room.remotePublishedUserMap.get(a);d==null||d.setDelay({videoDelay:o,audioDelay:n})}})}};c(Fs,"EVENT_NETWORK_QUALITY","0"),c(Fs,"lastPingTime",0);var Ho=Fs;function MS({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return Wr(t)?t.catch(r=>z.error(`${s.name}() error observed ${r}`)):t}catch(t){z.error(`${s.name}() error observed ${t}`)}}}var Lc=class{constructor(i){c(this,"_frameWorkType");c(this,"_component");c(this,"_language");c(this,"connectionType");c(this,"_room");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});c(this,"_keyPrefix");c(this,"_log");c(this,"_intervalId");c(this,"_firstPublishedUserList");c(this,"_networkQuality");c(this,"_basicInfo");c(this,"_pathJoinRoom");c(this,"_pathLeaveRoom");c(this,"_pathMainVideoMap");c(this,"_pathMainAudioMap");c(this,"_pathAuxiliaryMap");c(this,"_remoteStreamStatMap");c(this,"_localStreamStat");c(this,"_eventMap",new Map);c(this,"_captureCostSum",0);c(this,"_captureCostCount",0);c(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=z.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Fe(this[e])&&(this[e]=MS({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:Rt,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,Es().then(i=>{this._basicInfo.string_os_version=gr(),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),x.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(B.JOIN_START,this.handleJoinStart).addEvent(B.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(B.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(B.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(B.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(B.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(B.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(B.JOIN_FAILED,this.handleJoinFailed).addEvent(B.LEAVE_START,this.handleLeaveStart).addEvent(B.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(B.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(B.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(B.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(B.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(B.PUBLISH_START,this.handlePublishStart).addEvent(B.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(B.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(B.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(B.PLAY_TRACK_START,this.handlePlayStart).addEvent(B.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(B.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===S.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(B.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(B.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(B.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(B.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(B.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>x.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Le.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&&(M(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),M(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),M(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:o,tcp:n,tls:a,request:d,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof X?Number(e.getExtraCode()||e.getCode()):H.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:de(Z({},xS),{msg_user_info:new ga({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,d=new ga({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),h=`${o}_${t}`,u=this._remoteStreamStatMap.get(h);u&&u.subscribeStartTime===0&&(u.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(h)&&this._pathMainVideoMap.set(h,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(h)&&this._pathMainAudioMap.set(h,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(h)&&this._pathAuxiliaryMap.set(h,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,Q.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,l,h,u;o&&(l=o,h=1),n&&(d=n,u=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:d,totalVideoDelay:l,audioDelayCount:u,videoDelayCount:h})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height: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/ai*100)>0&&(this._localStreamStat.totalAudioLevel+=o/ai,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:d}=o,l=n.str_identifier,h=this._room.remotePublishedUserMap.get(l);if(d.forEach(u=>{let m=u.uint32_video_stream_type===2,p=u.uint32_video_stream_type===7,g=`${l}_${m?"main":"auxiliary"}`,f=this._remoteStreamStatMap.get(g);if(f&&(m&&(h!=null&&h.remoteVideoTrack.isSubscribed)||p&&(h!=null&&h.remoteAuxiliaryTrack))){f.totalVideoFPS+=u.uint32_video_receive_fps,f.totalVideoBitrate+=u.uint32_video_codec_bitrate,f.videoCount++,f.statsToReport.uint32_video_width===0&&(f.statsToReport.uint32_video_width=u.uint32_video_width),f.statsToReport.uint32_video_height===0&&(f.statsToReport.uint32_video_height=u.uint32_video_height);let T=m?h.remoteVideoTrack:h.remoteAuxiliaryTrack;T.stat.jitterBufferDelay&&(f.videoJitterBufferDelay=T.stat.jitterBufferDelay),T.stat.framesReceived&&(f.statsToReport.uint32_video_consume_render_rate=Math.floor(T.stat.framesDecoded/T.stat.framesReceived*Xo(10,6)))}}),!Ys(a)){let u=`${l}_main`,m=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&m&&h!=null&&h.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/ai*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/ai,m.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof X?e.getExtraCode()||e.getCode():H.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Fr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Hr)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ds)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:h,count:u,audioDelayCount:m,videoDelayCount:p,totalAudioDelay:g,totalVideoDelay:f}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(h/u),m&&g&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(g/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),p&&f&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(f/p))}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,S.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,S.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Hs));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:d}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=d,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Hs&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Hs)}),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>Hs&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Hs)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Hs&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Hs)}getReportData(){this._basicInfo.uint32_networkType=ps();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ga({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()*Xo(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,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return un(i),i}report(){return A(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 A(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield fl(i),r=t instanceof ArrayBuffer,o=`${lr(e,$r.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(Q),this.uploadKVStat(Cs)];n||a.push(mr({url:o,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return A(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=de(Z({},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 fl(e),r=`${lr(+this._room.sdkAppId,$r.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||mr({url:r,body:t})})}};J([Gt({settings:{timeout:500,retries:3}})],Lc.prototype,"upload",1);var Hs=5e3,xS={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},ga=class{constructor(i){c(this,"str_identifier");c(this,"str_tinyid");c(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},h_=Lc;var Zh=class{constructor(){c(this,"_startTime");c(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=le())}stop(){this._endTime===0&&(this._endTime=le())}getDuration(){return this._endTime===0?le()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Pc=Zh;var Kh=class{constructor(i){c(this,"_room",null);c(this,"_durationMap");c(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(B.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(B.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(B.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`,S.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,S.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,S.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);o&&(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,S.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,S.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,S.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>x.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>x.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new Pc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===S.AUDIO?[o]:[],video:e===S.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()}},m_=Kh;var em=class{constructor(i){c(this,"_room");c(this,"_renderFreezeMap",new Map);c(this,"_isVideoPlayingEventFiredMap",new Map);c(this,"_dataFreezeMap",new Map);c(this,"_monitorFreezeData",new Map);c(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(B.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(B.PLAY_TRACK_START,this.onPlayTrackStart).set(B.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(B.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(B.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==S.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===S.MUTE?this.onVideoTrackMuted(i):t===S.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(B.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>x.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>x.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 Pc;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>xa?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 A(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=le();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=le();let d=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,d)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==S.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<xa&&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=le(),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()}},p_=em;var __=gt(Mt(),1);var LS=[1,0,0,0,1,1,0,1],Uc=class extends Bt{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof mt)try{this.setTexBuffer(LS)}catch(t){i.destroy(new X({code:H.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 tm=class{constructor(i,e){this.node=i;this.layout=e;c(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Vc=class extends Bt{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});c(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new tm(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 mt&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((r,o)=>(!o||!o.node.requestFrame(e))&&r,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:d,fps:l,name:a},Z({parent:this.inputs.filter(h=>h).map(h=>h.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof mt))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var PS=`#version 300 es
70
82
  in vec2 a_position;
71
83
  in vec2 a_texCoord;
72
84
  out vec2 v_texCoord;
73
85
  void main() {
74
86
  gl_Position = vec4(a_position.x, a_position.y, 0, 1);
75
87
  v_texCoord = a_texCoord;
76
- }`,tE=`#version 300 es
88
+ }`,US=`#version 300 es
77
89
  precision highp float;
78
90
  uniform sampler2D u_texture;
79
91
  uniform sampler2D mask;
@@ -82,7 +94,7 @@ in vec2 v_texCoord;
82
94
  out vec4 outColor;
83
95
  void main() {
84
96
  outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
85
- }`,Sc=class extends Vi{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentation");d(this,"wasm");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_enableFaceCentering",!1);d(this,"_mat4");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 y({code:S.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))}}init(e){var o;let t=e.Wasm,r=this.context.ctx;if(this._mat4=e.mat4,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,this._enableFaceCentering=(o=e.enableFaceCentering)!=null?o:!1,e.waterMark){let{x:n,y:a,width:c,height:l}=e.waterMark;this.wasm.setWaterMark(n,a,c,l)}if(e.beautyParams){let{beauty:n,brightness:a,ruddy:c}=e.beautyParams;this.wasm.setBeauty(n,a,c,e==null?void 0:e.width,e==null?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,this._mat4.create()),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,this._mat4.create()),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let n=this.context.createShader(r.FRAGMENT_SHADER,tE),a=this.context.createShader(r.VERTEX_SHADER,eE);this._prePrograme=this.context.createProgram(a,n),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableFaceCentering&&(this._centerFace=new Ec(this.wasm.vbMode,e.faceDetector,this.context.log))}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(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),t.drawArrays(t.TRIANGLE_STRIP,0,4)}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){var c,l,u,m;let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:o,videoHeight:n}=r;if(o===0||n===0||!this.available)return!1;r.width=o,r.height=n;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():(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),(l=this._selfieSegmentation)==null||l.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(u=this._selfieSegmentation)==null||u.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,o,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,o,n,0)),this.wasm.vbMode&&((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}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(e.canvas.width,e.canvas.height,t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){let o=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(o,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(o,o,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,o)}}drawImage(e,t,r,o,n,a){let c=this.context.ctx,l=this._mat4.create();this._mat4.fromTranslation(l,[r/e,1-(o+a)/t,0]),this._mat4.scale(l,l,[n/e,a/t,1]),c.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Ic=class extends tt{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
97
+ }`,Bc=class extends kr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});c(this,"_bgTexture");c(this,"_waterMarkTexture");c(this,"_lastMaskTexture");c(this,"_lastMaskFbo");c(this,"_textureValid",!1);c(this,"_selfieTextureValid",!1);c(this,"_selfieSegmentation");c(this,"wasm");c(this,"_prePrograme");c(this,"_segmentationMask");c(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(r){e.log.error(r),e.destroy(new X({code:H.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))}}init(e){let t=e.Wasm,r=this.context.ctx;if(this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:o,y:n,width:a,height:d}=e.waterMark;this.wasm.setWaterMark(o,n,a,d)}if(e.beautyParams){let{beauty:o,brightness:n,ruddy:a}=e.beautyParams;this.wasm.setBeauty(o,n,a,e==null?void 0:e.width,e==null?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let o=this.context.createShader(r.FRAGMENT_SHADER,US),n=this.context.createShader(r.VERTEX_SHADER,PS);this._prePrograme=this.context.createProgram(n,o),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var r;let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(r=this._selfieSegmentation)==null||r.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){var d,l,h,u;let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:o,videoHeight:n}=r;if(o===0||n===0||!this.available)return!1;r.width=o,r.height=n;let a=!1;if(this.totalFrames)this._weixin?this.useTexture():(d=this._selfieSegmentation)==null||d.bindTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}return this.width!==o||this.height!==n||!a?(this.resize(o,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(l=this._selfieSegmentation)==null||l.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(h=this._selfieSegmentation)==null||h.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,o,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,o,n,0)),this.wasm.vbMode&&((u=this._selfieSegmentation)==null||u.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 $c=class extends Bt{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
86
98
  precision highp float;
87
99
  uniform sampler2D ySampler;
88
100
  uniform sampler2D uSampler;
@@ -107,15 +119,28 @@ void main() {
107
119
  void main() {
108
120
  gl_Position = vertexPos;
109
121
  textureCoord = texturePos;
110
- }`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,o=r.createTexture();return r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),o}render(e){let t=this.context.ctx,r=this.width,o=this.height;return this.useProgram(),t.viewport(0,0,r,o),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,o,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var Ou=[s=>{s.codec="avc1.42e01f"},s=>{delete s.hardwareAcceleration}],Op=(s,i)=>{switch(s){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function iE(s){return s[0]===0&&s[1]===0&&s[2]===0&&s[3]===1}var rE=0,Ac=class{constructor(i){d(this,"id",rE++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=et(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=me(e.availableState,$.OFF),this.stopOB=et(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),le(this.stateChangeOB,Fl((r,o)=>(r!==o&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:o}),o),"INITIALIZED"),xe(this.stopOB),ye()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=le(this.pipe(this.track),xe(this.stopOB),xi());le(e,ye(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),b.addFailedEvent({key:Op(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),b.addSuccessEvent({key:Op(this.type,this.renderer)}),b.addSuccessEvent({key:514704})})),le(e,Ui(1),ye(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!vo()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!iE(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,o=!1;switch(r){case 5:case 7:o=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),o&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(o)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=x();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(c=i.getMetadata)==null?void 0:c.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>p(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:o,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":for(let c=0;c<=Ou.length;c++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(c===Ou.length){e.error(3);return}Ou[c](this.config)}t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&o==="webgl"){this.videoContext=new Oe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Oe.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new Ic(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(o==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new je({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{c.image=u,c.update()}catch(m){delete this.goodType,i.log.error(m),e.error(11)}});let l=new Vr(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var un=class extends kp.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"cameraTrack");d(this,"cameraNode");d(this,"mirrorNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"_enableFaceCentering",!1);d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log",C.createLogger({id:"vm"}));d(this,"_faceDetector");d(this,"_mat4");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"_selfieSegmentation");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new je({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new 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(Oe.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),oe.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Zi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?b.addFailedEvent({key:r,error:t}):b.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 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,t,r){return this._selfieSegmentation=e,this._faceDetector=t,this._mat4=r,this._selfieSegmentation.changeModel()}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new qa(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Oe.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:o}=this.cameraTrack.settings;this.smallTrackSource.resize(r,o),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:o,player:n}=r;Zi&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(o,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return p(this,null,function*(){var o,n,a;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),lt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Vi?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Vi?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new ja(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Sc(this.videoContext,{input:this.initialTrack,width:t.width,height:t.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,faceDetector:this._faceDetector,mat4:this._mat4}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let c=this.cameraNode;c.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new gc(this.videoContext,this.log)),c=c.connect(this.mirrorNode),c.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Tc(this.videoContext,this.log),c.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption?(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y):(o=this.waterMarkNode)==null||o.resize(t.width,t.height),(n=this.waterMarkNode)==null||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(a=this.screenNode)==null||a.connect(this.mixNode,{zIndex:0}),c=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),c.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof at)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Je)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof ui){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof at?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Je?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ui&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update(!0)})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return p(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let o=r.getContext("2d");if(!o)throw new y({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:u})=>{o.drawImage(n,a,c,l,u)}),is(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return p(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return p(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return p(this,null,function*(){var m,f;let t;try{t=yield is((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new y({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some(g=>g.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==c),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((m=this.cameraTrack)==null?void 0:m.settings.width,(f=this.cameraTrack)==null?void 0:f.settings.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,D)=>g==="imageUrl"?void 0:D))})}deleteWatermark(e="watermark"){return p(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var t,r,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((r=this.cameraTrack)==null?void 0:r.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return p(this,null,function*(){var t;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 is(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new y({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return p(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Ac(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};N([ba(function(e){this.log.error("update failed",e)})],un.prototype,"update",1);var sE=0;var Cc=class extends ${constructor(e){super("room");d(this,"seq",++sE);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"smallMode","canvas");d(this,"_isUsingCachedSchedule",!1);d(this,"_log",C.createLogger({id:`r${this.seq}`}));d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,he(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),he(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),he(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new vp({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Np({room:this}),this.badCaseDetector=new Dp({room:this}),this.audioManager=new ka(this),this.videoManager=new un(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return p(this,null,function*(){return this.publish(e)})}removeTrack(e){return p(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return p(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(K(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(He(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(Ka([a,a]),ur(`https://${a}`)):(o&&ur(o),n&&Ka(n))}E.once(I.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:lr.main,sched_back_domain:lr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return p(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return p(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let o=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new y({code:S.INVALID_OPERATION,message:P({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(we.INVALID_DESTROY),new y({code:S.INVALID_OPERATION,message:P({key:L.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,E.emit(I.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var o,n,a,c;let r=x();try{let{isCached:l,result:u,detailCost:m}=yield Zl({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ke,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${gt(u,{keysToExclude:["username","credential"]})}`),l&&E.once(I.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),u),J((o=u.config)==null?void 0:o.retryCount)&&$c(u.config.retryCount),K((n=u.config)==null?void 0:n.loggerDomain)&&ur(u.config.loggerDomain),this.videoDecodeFallbackType=((a=u.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=u.config)==null?void 0:c.smallMode)||this.smallMode,E.emit(I.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:m}),b.addSuccessEvent({key:521700,cost:x()-r})}catch(l){throw b.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var Gp=Be(Qe());var ku=Be(Iu());var Mp=s=>{let i=Ce(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&&!T(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 Lp(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 oE(){return p(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=Ce(i.sdp),t=Lp(e.media[0]);return s.close(),t})}var Pp=(s,i)=>p(void 0,null,function*(){var c;let e=Ce(s),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(l=>({id:l.value,uri:l.uri}))),o.ext&&(t.video.extensions=o.ext.map(l=>({id:l.value,uri:l.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(c=r.rtcpFb)==null||c.forEach(({payload:l,type:u,subtype:m})=>{if(l===n.payload){let f={id:u,params:[]};m&&f.params.push(m),n.rtcpfb.push(f)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...Lp(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield oE()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),wp=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Ce(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(Mu({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),At(o)},Mu=({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=>{Jr(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];Jr(o,a)}return o},Jr=(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 nE(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 aE(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 cE(s){s.type===h.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function dE(s){s.type===h.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var xp=(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)&&(aE(r),cE(r),dE(r),nE(r),r.type===h.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Jr(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=>Jr(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),ku.default.write(t)};var Up=Be(Qe());var Rc=class extends Up.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!pe&&Ye&&E.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:o}){if(!(e||t===7||o!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){E.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(Rc,"EVENT_BAD_HEALTH","bad_health");var Vp=Rc;function Bp({seiMessageList:s,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(o)}})}function Fp(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function $p(s){let i=[Pi],e=[cu,nu,au,ou,Bp,Fp],t=()=>{let l=[],u=[],m=[];self.onmessage=f=>{f.data.type==="sei"&&(f.data.isMain?(l.push(f.data.data),f.data.small&&m.push(f.data.data)):u.push(f.data.data))},self.onrtctransform=f=>{let{options:g}=f.transformer,D=g.isReceiver?Fp(g.userId,g.streamType,g.isAudio):Bp({isAudio:g.isAudio,seiMessageList:g.isMain?g.small?m:l:u,isMain:g.isMain});f.transformer.readable.pipeThrough(D).pipeTo(f.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
122
+ }`});c(this,"yTextureRef");c(this,"uTextureRef");c(this,"vTextureRef");c(this,"Y");c(this,"U");c(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,o=r.createTexture();return r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),o}render(e){let t=this.context.ctx,r=this.width,o=this.height;return this.useProgram(),t.viewport(0,0,r,o),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,o,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var im=[s=>{s.codec="avc1.420028"},s=>{delete s.hardwareAcceleration}],f_=(s,i)=>{switch(s){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function VS(s){return s[0]===0&&s[1]===0&&s[2]===0&&s[3]===1}var BS=0,Fc=class{constructor(i){c(this,"id",BS++);c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"decoder");c(this,"videoContext");c(this,"gop",0);c(this,"gop_helper",0);c(this,"waitFirstKeyFrame",!0);c(this,"startTimestamp",0);c(this,"startTime",0);c(this,"startPerformanceTime",0);c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"decodeFrameCount",0);c(this,"downgradeLevel",0);c(this,"lastDowngradeTime",0);c(this,"lastFrameDiff",0);c(this,"lastDecodeFrameTimestamp",0);c(this,"config");c(this,"gop_before_configure",[]);c(this,"videoElement");c(this,"type","wasm");c(this,"goodType");c(this,"renderer","2d");c(this,"wasmOption");c(this,"createDecoder");c(this,"_decodeSink");c(this,"isReported",!1);c(this,"track");c(this,"stateChangeOB");c(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=Vt(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=We(e.availableState,ge.OFF),this.stopOB=Vt(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),He(this.stateChangeOB,rh((r,o)=>(r!==o&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:o}),o),"INITIALIZED"),St(this.stopOB),it()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=He(this.pipe(this.track),St(this.stopOB),Nr());He(e,it(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),Q.addFailedEvent({key:f_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),Q.addSuccessEvent({key:f_(this.type,this.renderer)}),Q.addSuccessEvent({key:514704})})),He(e,Dr(1),it(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!tu()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,d;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!VS(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,o=!1;switch(r){case 5:case 7:o=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),o&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(o)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=le();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(d=i.getMetadata)==null?void 0:d.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>A(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:o,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":for(let d=0;d<=im.length;d++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(d===im.length){e.error(3);return}im[d](this.config)}t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",d=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${d.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(d.timestamp)),e.next(d)}),t.on("error",d=>{i.log.error(d),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&o==="webgl"){this.videoContext=new mt({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(mt.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let d=new $c(this.videoContext);t.on("videoCodecInfo",l=>d.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:d.Y,u:d.U,v:d.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&d.render(this.decodedFrameCount):d.render(this.decodedFrameCount)}),i.source=d,i.player.setCanvas(this.videoContext._canvas,2)}else if(o==="videoFrame"){i.player.setCanvas();let d=new MediaStreamTrackGenerator({kind:"video"}),l=d.writable.getWriter();i.setInputMediaStreamTrack(d),t.on("videoFrame",h=>l.write(h))}else{this.videoContext=new Dt({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let d=this.videoContext.createVideoImageSource();t.on("videoFrame",h=>{try{d.image=h,d.update()}catch(u){delete this.goodType,i.log.error(u),e.error(11)}});let l=new xs(this.videoContext,{name:"remotePlayer",logger:i.log});d.connect(l),i.source=d,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var Ea=class extends __.EventEmitter{constructor(e){super();this.room=e;c(this,"videoContext");c(this,"_glVideoContext");c(this,"_2dVideoContext");c(this,"destination");c(this,"smallVideoContext");c(this,"smallDestination");c(this,"smallTrackSource");c(this,"smallImageSource");c(this,"_isMirror",!1);c(this,"cameraTrack");c(this,"cameraNode");c(this,"mirrorNode");c(this,"mixNode");c(this,"screenTrack");c(this,"screenNode");c(this,"selfModel",!1);c(this,"blurRadius",3);c(this,"arTrack");c(this,"Wasm");c(this,"waterMarkNode");c(this,"_waterMarkOption");c(this,"watermarkImageList",[]);c(this,"_beautyParams");c(this,"isUsingArTrack",!1);c(this,"_isMixScreen",!1);c(this,"_virtualBackground");c(this,"_virtualBackgroundAbortCallback");c(this,"virtualBackgroundInstance");c(this,"_bgAssetPath");c(this,"log",z.createLogger({id:"vm"}));c(this,"_checkId",0);c(this,"_use2d",!1);c(this,"_autoSwitchRenderMode",!0);c(this,"_selfieSegmentation");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Dt({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 Dt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new mt({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(mt.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=Le.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Le.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 r=e==="videoCtxGl"?512700:512701;t?Q.addFailedEvent({key:r,error:t}):Q.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 mt({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}setSmallVideo(e,t){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new ic(this.smallVideoContext,e,this.log),this.smallVideoContext.on(mt.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:o}=this.cameraTrack.settings;this.smallTrackSource.resize(r,o),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:o,player:n}=r;this.setSmallVideo(o,e),jr&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${a?a.label:"no output track"}`),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return A(this,null,function*(){var o,n,a;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),Xt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof kr?(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 kr?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new tc(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new Bc(this.videoContext,{input:this.initialTrack,width:t.width,height:t.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let d=this.cameraNode;d.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Uc(this.videoContext,this.log)),d=d.connect(this.mirrorNode),d.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Vc(this.videoContext,this.log),d.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption?(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y):(o=this.waterMarkNode)==null||o.resize(t.width,t.height),(n=this.waterMarkNode)==null||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(a=this.screenNode)==null||a.connect(this.mixNode,{zIndex:0}),d=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),d.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof jt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Nt)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof er){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof jt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Nt?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof er&&e.source&&e.source.context.destroy()}setCameraTrack(e){return A(this,null,function*(){this.cameraTrack=e,this.update(!0)})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return A(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 X({code:H.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:d,width:l,height:h})=>{o.drawImage(n,a,d,l,h)}),eo(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 A(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return A(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return A(this,null,function*(){var u,m;let t;try{t=yield eo((e==null?void 0:e.imageElement)||e.imageUrl)}catch(p){throw new X({code:H.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:d="watermark",zIndex:l=2}=e;this.watermarkImageList.some(p=>p.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(p=>p.type!==d),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((u=this.cameraTrack)==null?void 0:u.settings.width,(m=this.cameraTrack)==null?void 0:m.settings.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(p,g)=>p==="imageUrl"?void 0:g))})}deleteWatermark(e="watermark"){return A(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return A(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 A(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 eo(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 X({code:H.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 A(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Fc(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};J([Ld(function(e){this.log.error("update failed",e)})],Ea.prototype,"update",1);var $S=0;var Hc=class extends ge{constructor(e){super("room");c(this,"seq",++$S);c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"privateMapKey");c(this,"latencyLevel");c(this,"tinyId");c(this,"scene");c(this,"roomId");c(this,"useStringRoomId");c(this,"role","anchor");c(this,"joinParams",null);c(this,"localTracks",new Set);c(this,"enableAutoPlayDialog",!0);c(this,"autoReceiveAudio",!0);c(this,"autoReceiveVideo",!0);c(this,"proxy_ws");c(this,"proxy_wt");c(this,"proxy_unified");c(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}});c(this,"keyPointManager");c(this,"audioManager");c(this,"videoManager");c(this,"callDurationCalculator");c(this,"badCaseDetector");c(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});c(this,"videoDecodeFallbackType");c(this,"_isUsingCachedSchedule",!1);c(this,"_log",z.createLogger({id:`r${this.seq}`}));c(this,"_joinedTimestamp",0);c(this,"_sdkType");c(this,"heartbeatReport");c(this,"quality");c(this,"enableSEI");c(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,Qe(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Qe(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Qe(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new h_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new m_({room:this}),this.badCaseDetector=new p_({room:this}),this.audioManager=new $d(this),this.videoManager=new Ea(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 A(this,null,function*(){return this.publish(e)})}removeTrack(e){return A(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return A(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Oe(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Ht(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?(ac([a,a]),as(`https://${a}`)):(o&&as(o),n&&ac(n))}x.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:tr.main,sched_back_domain:tr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return A(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return A(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 A(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 X({code:H.INVALID_OPERATION,message:pe({key:me.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Tt.INVALID_DESTROY),new X({code:H.INVALID_OPERATION,message:pe({key:me.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,x.emit(B.ROOM_DESTROY,{room:this})}schedule(e,t){return A(this,null,function*(){var o,n,a;let r=le();try{let{isCached:d,result:l,detailCost:h}=yield fh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Rt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=d,this._log.info(`schedule cache:${+d} ${oi(l,{keysToExclude:["username","credential"]})}`),d&&x.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Z(Z({},this.scheduleResult),l),De((o=l.config)==null?void 0:o.retryCount)&&nl(l.config.retryCount),Oe((n=l.config)==null?void 0:n.loggerDomain)&&as(l.config.loggerDomain),this.videoDecodeFallbackType=((a=l.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,x.emit(B.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),Q.addSuccessEvent({key:521700,cost:le()-r,split:50})}catch(d){throw Q.addFailedEvent({key:521700,error:d}),d}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var N_=gt(Mt());var rm=gt(Jh());var g_=s=>{let i=et(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&&!M(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(d=>d.attribute==="cname")[1])==null?void 0:o.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function E_(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 FS(){return A(this,null,function*(){let s=new RTCPeerConnection;s.addTransceiver(S.VIDEO,{direction:S.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield s.createOffer();if(!i.sdp)return[];let e=et(i.sdp),t=E_(e.media[0]);return s.close(),t})}var T_=(s,i)=>A(void 0,null,function*(){var d;let e=et(s),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(l=>({id:l.value,uri:l.uri}))),o.ext&&(t.video.extensions=o.ext.map(l=>({id:l.value,uri:l.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(d=r.rtcpFb)==null||d.forEach(({payload:l,type:h,subtype:u})=>{if(l===n.payload){let m={id:h,params:[]};u&&m.params.push(u),n.rtcpfb.push(m)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...E_(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield FS()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),S_=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=et(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:S.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:S.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(sm({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),li(o)},sm=({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:S.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:S.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=>{Gs(o,a)})}else{let n=i.video.codecs.findIndex(d=>d.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];Gs(o,a)}return o},Gs=(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 HS(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 GS(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 WS(s){s.type===S.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function zS(s){s.type===S.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var I_=(s,i,e)=>{let t=rm.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===S.AUDIO||r.type===S.VIDEO)&&(GS(r),WS(r),zS(r),HS(r),r.type===S.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Gs(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(d=>Gs(r,d))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),rm.default.write(t)};var A_=gt(Mt());var Gc=class extends A_.EventEmitter{constructor(e){super();this.room=e;c(this,"mainFpsHealth",1);c(this,"mainBitrateHealth",1);c(this,"badMainBitrateHealthCount",0);c(this,"lastEmitBadHealthTime",0);c(this,"log");!ze&&xt&&x.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(){x.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};c(Gc,"EVENT_BAD_HEALTH","bad_health");var C_=Gc;function R_({seiMessageList:s,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(o)}})}function y_(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(d=>{self.postMessage({type:"sei",seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function b_(s){let i=[vr],e=[bh,Rh,yh,Ch,R_,y_],t=()=>{let l=[],h=[],u=[];self.onmessage=m=>{m.data.type==="sei"&&(m.data.isMain?(l.push(m.data.data),m.data.small&&u.push(m.data.data)):h.push(m.data.data))},self.onrtctransform=m=>{let{options:p}=m.transformer,g=p.isReceiver?y_(p.userId,p.streamType,p.isAudio):R_({isAudio:p.isAudio,seiMessageList:p.isMain?p.small?u:l:h,isMain:p.isMain});m.transformer.readable.pipeThrough(g).pipeTo(m.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
111
123
  const videoDecodePipeline=[${s.videoDecodePipeline.toString()}];
112
124
  const audioEncodePipeline = [${s.audioEncodePipeline.toString()}];
113
125
  const audioDecodePipeline = [${s.audioDecodePipeline.toString()}];`,o=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
114
126
  `)}
115
127
  ${e.map(l=>l.toString()).join(`
116
- `)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var hi=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(hi||{}),Wp=0,Jp=!1,lE=new Set,uE=s=>Wp>2&&!Jp&&lE.size===0&&s,mE=1,Ft=class extends Gp.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);d(this,"originOffer",null);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=C.createLogger({id:`spc${mE++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Oi?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,r;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?Mp(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){this.useHWEncoder(!1,e?7:2)}initScriptTransformWorker(){Ss&&(this.scriptTransformWorker=$p({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"&&this.emit("sei-message",e.data),e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var o;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(o=this._peerConnection)==null?void 0:o.getConfiguration().encodedInsertableStreams;return Pn(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return p(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let o=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${o}`),o==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():o==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),b.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):o==="failed"&&b.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let o=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[o==="closed"?"debug":"info"](`signaling state: ${o}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=o=>this.emit("track",o),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=o=>{let n=new Pu(o.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=o=>{this._log.warn("datachannel error",o)}),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}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield Pp(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:o}=this;o&&(this._log.debug(`dtls state: ${o.state}`),o.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():o.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),b.addSuccessEvent({key:521707}),this.clientAbility}catch(o){throw b.addFailedEvent({key:521707,error:o}),this._log.error(`initialize failed ${o}
117
- offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return p(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return p(this,null,function*(){var r,o,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=x(),c={type:"answer",sdp:wp({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(c),yield this.waitForPeerConnectionConnected();let l=((o=this._room.scheduleResult.config)==null?void 0:o.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||b.addSuccessEvent({key:521703,cost:x()-a})}catch(a){let c=a instanceof y&&a.code===S.API_CALL_ABORTED;throw c||this._log.error(`connect failed: ${a}`,e),this.reset(),!c&&!this.isReconnecting&&(b.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return p(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(be.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=v({ability:t},e),o=yield this._signalChannel.sendWaitForResponse({command:Q.REBUILD_PEER_CONNECTION,responseCommand:H.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(o.data.code!==0)throw new y({code:o.data.code,message:o.data.message});yield this.connect(o.data.data.ability,!0),b.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),E.emit(I.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Nt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ii(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),b.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=gi()&&this._log.warn(`SDK has tried reconnect for ${gi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return p(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(be.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===fe.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var o;let t=((o=this._peerConnection)==null?void 0:o.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===fe.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===fe.FAILED||e.target.connectionState===fe.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===fe.CONNECTED||e.target.connectionState===fe.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),E.emit(I.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return yt;let e=null;return!ir()||this._peerConnection.getSenders().length===0?yt:(e=this._peerConnection.getSenders()[0].transport,!vr()||this._peerConnection.getReceivers().length===0?yt:e?e.state:yt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(hi.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(tr(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&&Nn(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{E.off(I.LEAVE_SUCCESS,o,this),this.off(hi.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Wp+=1,uE(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Jp=!0,this.emit(hi.FIREWALL_RESTRICTION)),t(c)},Ks);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},E.on(I.LEAVE_SUCCESS,o,this),this.on(hi.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return p(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(f=>f.direction==="inactive").slice(0,3).map(f=>(f.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(f.mid)));this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(f=>{var g;return(g=f.ssrcs)==null?void 0:g.find(D=>{var _;return(_=D.value)==null?void 0:_.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[0])),c=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[1])),l=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(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 f=Mu({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ce(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(f)),l=JSON.parse(JSON.stringify(f)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${h.MAIN} ${u}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${h.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${h.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${u}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${u}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${u}-aux${h.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(f=>f.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return p(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(Oo()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],m;l===0&&t?m=t:l===1&&r?m=r:l===2&&o?m=o:l===3&&n&&(m=n),m&&(yield this.setSenderMaxBitrate(u,m))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=Ce(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=Ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp));let a=ae?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ae?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ae?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ae?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ae?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:ae?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ae?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:ae?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ae?o*1e3:o}]);let c={type:"offer",sdp:At(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(T(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}setDegradationPreference(e,t,r){if(Ye&&dt<83||Ie&&ld(Xt,"12.1")||ae&&no<138)return;let o=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),o.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),o.degradationPreference=n,e.setParameters(o).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=At(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>p(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
128
+ `)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),d=new Worker(a);return URL.revokeObjectURL(a),d}var sr=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(sr||{}),D_=0,k_=!1,jS=new Set,JS=s=>D_>2&&!k_&&jS.size===0&&s,qS=1,vi=class extends N_.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();c(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});c(this,"currentState","DISCONNECTED");c(this,"_room");c(this,"_signalChannel");c(this,"_peerConnection",null);c(this,"_datachannel",null);c(this,"_enableCustomMessage");c(this,"_log");c(this,"_downlinkMIDMap",new Map);c(this,"_downlinkMIDUserIDMap",new Map);c(this,"_reconnectionTimer",-1);c(this,"reconnectionCount",0);c(this,"clientAbility");c(this,"_serverAbility",null);c(this,"addDownlinkQueue",new Set);c(this,"removeDownlinkQueue",new Set);c(this,"_parsedAnswer",null);c(this,"_updateSDPPromise",null);c(this,"_waitForPCConnectedPromise");c(this,"clearWaitForConnectedPromise");c(this,"clearConnectTimeout");c(this,"_isSDPLogged",!1);c(this,"enableInsertableStreams",!1);c(this,"insertableStreamsAbortMap",new Map);c(this,"receiverRemoteTrackMap",new WeakMap);c(this,"scriptTransformWorker");c(this,"_isRelayTried",!1);c(this,"_rttOverCount",0);c(this,"originOffer",null);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=z.createLogger({id:`spc${qS++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Ar?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,r;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?g_(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(){Sd&&(this.scriptTransformWorker=b_({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"&&this.emit("sei-message",e.data),e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var o;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(o=this._peerConnection)==null?void 0:o.getConfiguration().encodedInsertableStreams;return Ga(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return A(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let o=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${o}`),o==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():o==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),Q.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):o==="failed"&&Q.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let o=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[o==="closed"?"debug":"info"](`signaling state: ${o}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=o=>this.emit("track",o),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=o=>{let n=new nm(o.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=o=>{this._log.warn("datachannel error",o)}),this._peerConnection.addTransceiver(S.AUDIO,{direction:S.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:S.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:S.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:S.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield T_(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:o}=this;o&&(this._log.debug(`dtls state: ${o.state}`),o.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():o.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),Q.addSuccessEvent({key:521707}),this.clientAbility}catch(o){throw Q.addFailedEvent({key:521707,error:o}),this._log.error(`initialize failed ${o}
129
+ offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return A(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return A(this,null,function*(){var r,o,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=le(),d={type:"answer",sdp:S_({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(d),yield this.waitForPeerConnectionConnected();let l=((o=this._room.scheduleResult.config)==null?void 0:o.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||Q.addSuccessEvent({key:521703,cost:le()-a})}catch(a){let d=a instanceof X&&a.code===H.API_CALL_ABORTED;throw d||this._log.error(`connect failed: ${a}`,e),this.reset(),!d&&!this.isReconnecting&&(Q.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return A(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(rt.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=Z({ability:t},e),o=yield this._signalChannel.sendWaitForResponse({command:ve.REBUILD_PEER_CONNECTION,responseCommand:Ee.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(o.data.code!==0)throw new X({code:o.data.code,message:o.data.message});yield this.connect(o.data.data.ability,!0),Q.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),x.emit(B.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=pi(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield hr(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),Q.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=dr()&&this._log.warn(`SDK has tried reconnect for ${dr()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return A(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(rt.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Je.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var o;let t=((o=this._peerConnection)==null?void 0:o.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===Je.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Je.FAILED||e.target.connectionState===Je.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Je.CONNECTED||e.target.connectionState===Je.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),x.emit(B.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 hi;let e=null;return!Qr()||this._peerConnection.getSenders().length===0?hi:(e=this._peerConnection.getSenders()[0].transport,!Rs()||this._peerConnection.getReceivers().length===0?hi:e?e.state:hi)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(sr.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return A(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Xr(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&&Pa(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=d=>{d.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:d})=>{d===this._room&&(clearTimeout(a),n(),t(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{x.off(B.LEAVE_SUCCESS,o,this),this.off(sr.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let d=new X({code:H.API_CALL_TIMEOUT,message:"connection timeout"});D_+=1,JS(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),k_=!0,this.emit(sr.FIREWALL_RESTRICTION)),t(d)},on);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new X({code:H.API_CALL_TIMEOUT,message:"connection timeout"}))},x.on(B.LEAVE_SUCCESS,o,this),this.on(sr.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 A(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=S.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=et(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var p;return(p=m.ssrcs)==null?void 0:p.find(g=>{var f;return(f=g.value)==null?void 0:f.includes(r)})}),a,d,l;if(n.length===3)a=n[0],d=n[1],l=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[0])),d=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[1])),l=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(S.AUDIO,{direction:S.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:S.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:S.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=sm({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:et(this._peerConnection.localDescription.sdp),isDownlink:!0});d=JSON.parse(JSON.stringify(m)),l=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=S.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${h}`},{id:e.audio,attribute:"msid",value:`${h}-${S.MAIN} ${h}-audio`}],d.direction=S.TRANSCEIVER_DIRECTION_SENDONLY,d.ssrcs=[{id:e.video,attribute:"cname",value:`${h}`},{id:e.video,attribute:"msid",value:`${h}-${S.MAIN} ${h}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${h}`},{id:e.videoRtx,attribute:"msid",value:`${h}-${S.MAIN} ${h}-bigvideo`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=S.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${h}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:u},{id:e.auxiliary,attribute:"msid",value:`${u} ${h}-aux${S.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${u} ${h}-aux${S.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${u} ${h}-aux${S.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,d.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return A(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=et(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 A(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(Mn()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let h=a[l],u;l===0&&t?u=t:l===1&&r?u=r:l===2&&o?u=o:l===3&&n&&(u=n),u&&(yield this.setSenderMaxBitrate(h,u))}let d=!1;r&&a[1].track&&(d=this.setStartBitrate(1,r)),n&&a[3].track&&(d=this.setStartBitrate(3,n)||d),d&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=et(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=et(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=et(this._peerConnection.remoteDescription.sdp));let a=Ue?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:Ue?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:Ue?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:Ue?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:Ue?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:Ue?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:Ue?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:Ue?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:Ue?o*1e3:o}]);let d={type:"offer",sdp:li(n)};return this.updateSDP({localDescription:d})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(M(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}setDegradationPreference(e,t,r){if(xt&&qt<83||Ye&&vl(Bi,"12.1")||Ue&&hn<138)return;let o=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),o.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),o.degradationPreference=n,e.setParameters(o).catch(d=>this._log.warn(`${a} failed: ${d}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=li(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>A(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(d){this._log.error(d),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
118
130
  next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
119
- next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:m,stopped:f})=>({mid:l,currentDirection:u,direction:m,stopped:f})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return p(this,null,function*(){if(!ae||!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===ee.INACTIVE&&n===ee.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===ee.SENDONLY&&n===ee.INACTIVE&&(this._parsedAnswer.media[o].direction=ee.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Ce(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=xp(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===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=[],Jr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];T(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(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Jr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Jt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),l=(this._isRelayTried||c>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return p(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),b.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),b.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};N([Da("reconnect")],Ft.prototype,"startReconnection",1),N([Li(e=>e.userId)],Ft.prototype,"addDownlink",1),N([Li(e=>e)],Ft.prototype,"removeDownlink",1),N([ni(!0)],Ft.prototype,"updateSDP",1),N([nt(521712,!1)],Ft.prototype,"setOffer",1),N([nt(521713,!1)],Ft.prototype,"setAnswer",1);var Lu=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Pu=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Lu(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Hp=new Set;function jr(){let s=Math.floor(Math.random()*4294967296);return Hp.has(s)?jr():(Hp.add(s),s)}var jp=Be(Qe());var qr=class extends jp.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=C.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(E.emit(I.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var wu=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");this._log=C.createLogger({id:"bvd",isLocal:!1})}getWorker(){if(!this.worker){let i=`
120
- const tracks=new Map,blackFramesCount={};let canvas,ctx;const log=(...a)=>postMessage({type:"log",message:"[worker] "+a.join(" ")});function handleAddTrack(e,a){blackFramesCount[e]=0;var t=setInterval(()=>{checkFrameBlack(e).then(a=>{a?(blackFramesCount[e]+=1,log(e+" black frames count: "+blackFramesCount[e]),3<=blackFramesCount[e]&&(postMessage({type:"black",trackId:e}),blackFramesCount[e]=0)):blackFramesCount[e]=0}).catch(a=>{log("Error checking frame:",a)})},1e3);tracks.set(e,{reader:a.getReader(),interval:t})}function handleRemoveTrack(a){blackFramesCount[a]=0;var e,t=tracks.get(a);t&&({reader:t,interval:e}=t,t.cancel(),clearInterval(e),tracks.delete(a))}async function checkFrameBlack(a){var e=tracks.get(a);if(!e)return log("track not found",a),!1;e=e.reader;try{var{done:t,value:r}=await e.read();if(t)return handleRemoveTrack(a),!1;if(!r)return!1;canvas||(canvas=new OffscreenCanvas(r.codedWidth,r.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===r.codedWidth&&canvas.height===r.codedHeight||(canvas.width=r.codedWidth,canvas.height=r.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(r,0,0,canvas.width,canvas.height);var c=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return r.close(),1===c}catch(a){return!1}}function getFrameBlackRatio(a){var e=a.data;let t=0;var r=e.length/4;for(let a=0;a<100;a++){var c=4*Math.floor(Math.random()*r),n=e[c],d=e[1+c],o=e[2+c];0!==e[3+c]&&0===n&&0===d&&0===o&&(t+=1)}return t/100}self.onmessage=a=>{var{type:a,trackId:e,readable:t}=a.data;"addTrack"===a&&handleAddTrack(e,t),"removeTrack"===a&&handleRemoveTrack(e)};
121
- `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t)}return this.worker}start(i,e){if(this._log.debug("start detect black video",i.id),!!vo())try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});return this.callbacks.set(i.id,e),t.onerror=o=>this._log.error("Worker error:",o),t.onmessage=o=>{var l;let{type:n,trackId:a,message:c}=o.data;n==="black"?(l=this.callbacks.get(a))==null||l():n==="log"&&this._log.warn(c)},t.postMessage({type:"addTrack",trackId:i.id,readable:r.readable},[r.readable]),i.id}catch(t){return this._log.warn("Failed to start black video detector:",t),null}}stop(i){var e;i&&((e=this.worker)==null||e.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i))}},Gi=new wu;var mn=class extends qr{constructor(e){super(w(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${bi()} ${Ar()}`),b.addCount({key:521e3});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.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&&(Kt()?(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 publishingState(){let{publishState:e}=this,t=v({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&Xi),bigVideo:!!(this.flag&qi),smallVideo:!!(this.flag&Ys),auxVideo:!!(this.flag&mr)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,m,f,g,D,_;if(!this.singlePC)return;this.installEvents(),yield Promise.all([this.singlePC.waitForPeerConnectionConnected(),this.singlePC.waitForReconnected()]);let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),pe&&hs()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(ji)}`),t.setProfile(ji),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:Q.SPC_PUBLISH,responseCommand:H.SPC_PUBLISH_RESULT,data:w(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:A}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],A,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(m=this.localMainVideoTrack)==null?void 0:m.profile.bitrate,smallVideo:(g=(f=this.localMainVideoTrack)==null?void 0:f.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],m=(g,D,_)=>{var O;let A=c[D].sender.replaceTrack(_);u.push(D),(O=this.singlePC)!=null&&O.enableInsertableStreams&&A.then(()=>this.createEncodedStreams(c[D].sender,g)),this.initSenderTransform(c[D].sender,g),l.push(A)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,o?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let f=this.singlePC.setTransceiverDirection(ee.SENDONLY,u);return l.push(f),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var f;let m=this.getTrackByMediaType(t);u.enqueue((f=this.singlePC)!=null&&f.isUsingH264&&m?m.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!Ss)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return p(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;let o=this._peerConnection.getTransceivers(),{sender:n}=o[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(b.addSuccessEvent({key:c}),!a){b.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ee.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),this._blackSmallVideoDetectionId=Gi.start(n.track,()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;b.addFailedEvent({key:u,error:10002}),Gi.stop(this._blackSmallVideoDetectionId)})})}doPublishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let o=this._peerConnection.getTransceivers(),{sender:n}=o[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=rs(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return p(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ee.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Gi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l,u;yield Promise.all([(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected(),(u=this.singlePC)==null?void 0:u.waitForReconnected()]);let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(ee.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Q.PUBLISH_STATE_CHANGE,data:t,responseCommand:H.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Q.UNPUBLISH,commandDesc:"unpublish",responseCommand:H.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),ei){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:H.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),Kt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===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&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ee.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ee.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),Kt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===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(ee.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?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 p(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:Q.UPDATE_MUTE_STAT,responseCommand:H.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(I.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===hr?(this._log.error(we.NOT_SUPPORTED_H264ENCODE),new y({code:S.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})})):new y({code:S.UNKNOWN,message:P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:H.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};N([Ke(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],mn.prototype,"publish",1),N([Ke(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],mn.prototype,"unpublish",1);var xu=mn;function qp(s){return Object.keys(s).filter(i=>s[i])}var Gs=class extends qr{constructor(e){super(w(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new wi(this._room,this),this.remoteVideoTrack=new ui(this._room,this),this.remoteAuxiliaryTrack=new Ms(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Si(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===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 u,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 l=this.remoteAudioTrack;c===h.VIDEO?l=this.remoteVideoTrack:c===h.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===h.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return p(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${qp(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);if(e.smallVideo){let{user:r,mediaTrack:o}=this.remoteVideoTrack;b.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Gi.start(o,()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,r),b.addFailedEvent({key:524702}),Gi.stop(this._blackSmallVideoDetectionId)})}else Gi.stop(this._blackSmallVideoDetectionId)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ye&&dt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${qp(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),t==="main"&&(Gi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Q.UNSUBSCRIBE,n=H.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Q.SUBSCRIBE_CHANGE,n=H.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:P({key:L.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return p(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:jr(),bigVideoSsrc:jr(),bigVideoRtxSsrc:jr(),auxVideoSsrc:jr(),auxVideoRtxSsrc:jr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Q.SPC_SUBSCRIBE,responseCommand:H.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0)throw new y({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!ma)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(J(n)||J(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return p(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!ma||!this.singlePC||!this._peerConnection||Ci(e)&&Ci(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return J(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),J(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Ci(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||Ci(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Ci(t)||!c&&Ci(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),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}};N([ni(),z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new y({code:S.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Gs.prototype,"subscribe",1),N([ni()],Gs.prototype,"unsubscribe",1),N([Li(()=>"jitter")],Gs.prototype,"setJitterBufferDelay",1);var Xp=Gs;function zp(){return z(s=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Qp(){return z(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Yp=Be(Qe());function pE(){return Math.floor(Math.random()*16383)}var bc=class bc extends Yp.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(H.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)||pE(),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(Q.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)>bc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Ii(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(bc,"SEQ_INTERVAL",300);var yc=bc;var{isString:Zp,isUndefined:Ws,getNetworkType:fE,isEmpty:hn}=ct,$t=class extends Cc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",Es);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new dn(this,this._log),this.userManager=new za(this.userId,this._log),this._version=ke,this.sdpSemantics=zr,Ws(e.sdpSemantics)?ti.isUnifiedPlanDefault()&&(this.sdpSemantics=zi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${fE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Ws(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Es,!Ws(e.enableSPC)&&Es&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Vp(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Fu(n,[]);E.emit(I.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},o))}),this.joinParams=e,new Promise((o,n)=>p(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof y&&u.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=x();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),b.addSuccessEvent({key:521708,cost:x()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){b.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Ft({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>p(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(be.SETUP_FAILED,m=>{this.clearJoinTimeout(),E.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),o(m)}),he((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&Es&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:_d(),netType:gr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:S.JOIN_ROOM_FAILED,message:P({key:L.JOIN_ROOM_TIMEOUT})}))},a),E.emit(I.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Q.SPC_JOIN_ROOM:Q.JOIN_ROOM,n),this.signalChannel.once(H.JOIN_ROOM_RESULT,m=>p(this,null,function*(){this.clearJoinTimeout();let{code:f,message:g,data:D,tinyId:_}=m.data;E.emit(I.JOIN_RECEIVED_CMD_RES,{room:this,code:f}),f===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var A;(A=this.singlePC)==null||A.connect(w(v({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${f} error: ${g}`),o(new y({code:S.JOIN_ROOM_FAILED,extraCode:f,message:P({key:L.JOIN_ROOM_FAILED,data:{error:g,code:f}})})))}))}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(w(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),ie.logSuccessEvent({userId:this.userId,eventType:rt.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(hi.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof xu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(hi.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof cn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),ie.logFailedEvent({userId:this.userId,eventType:rt.REJOIN,error:e}),this.emit("error",new y({code:S.JOIN_ROOM_FAILED,message:P({key:L.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||up(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new Vs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new yc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Hs({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Hs.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Ge(this,this.signalChannel).add(be.CONNECTION_STATE_CHANGED,a=>{E.emit(I.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(be.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(H.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(H.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(H.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(H.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(ie.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}),this.signalChannel.once(be.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(I.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||ve(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(I.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Q.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=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Dh(this.userId):[],o=w(v({str_sdk_version:Xs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:gr()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(I.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Q.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",w(v({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Uc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(I.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof cn&&(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?Xp:Ru)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",w(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Q.GET_USER_LIST,responseCommand:H.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:H.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||!Tu)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)===fe.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof it&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===fe.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ie.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new cn({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 Ru({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new y({code:S.INVALID_OPERATION,message:P({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Q.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:H.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new y({code:S.SWITCH_ROLE_FAILED,message:P({key:L.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new y({code:S.SWITCH_ROLE_FAILED,message:P({key:L.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return p(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Et&&(c instanceof ci?r.audio=c:t.audio=c),c instanceof Je&&(c instanceof at&&c.mediaType===2?r.video=c:t.video=c)});let o=hn(t),n=hn(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new xu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new cn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",w(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==S.ICE_TRANSPORT_ERROR&&(l===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Et&&(o instanceof ci?r.audio=o:t.audio=o),o instanceof Je&&(o instanceof at&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");hn(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),hn(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||!Vd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(I.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(I.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${pc(n)}] prev: [${pc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(I.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():S.UNKNOWN,c=n;throw n instanceof y?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:S.API_CALL_ABORTED,message:P({key:L.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:P({key:L.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(I.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(I.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var o;Or.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Or.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return p(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!Bd||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;J(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&J(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return p(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return p(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(ct.getTurnServer(o))):ct.isPlainObject(e)&&r.push(ct.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Q.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:H.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Q.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:H.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Q.START_PUBLISH_TENCENT_CDN:Q.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?H.START_PUBLISH_TENCENT_CDN_RES:H.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Q.STOP_PUBLISH_TENCENT_CDN:Q.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?H.STOP_PUBLISH_TENCENT_CDN_RES:H.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Q.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:H.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Q.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:H.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Q.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:H.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Q.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:H.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=ct.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Qr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Qr}catch(m){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Qr-a.reSubscribeCount}. reason: ${m}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Qr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Zp(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Ws(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Ws(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Ws(e.userDefinePushArgs))if(Zp(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new y({code:S.INVALID_PARAMETER,message:P({key:L.INVALID_USER_DEFINE_PUSH_ARGS})});hn(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return p(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Oi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}};N([_e(["left",$.INIT],"joined"),ht({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Vt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),np()],$t.prototype,"join",1),N([_e("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),ap(),Da("leave room"),Uo({fnName:"publish",validateArgs:!1}),Uo({fnName:"unsubscribe",validateArgs:!1})],$t.prototype,"leave",1),N([ni(),zp(),ht({settings:{retries:gi,timeout:e=>Nt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(I.PUBLISH_FAILED,{room:this}))}})],$t.prototype,"publish",1),N([Uo({fnName:"publish"}),fh("api-call"),ni(),Qp(),Ke(function(){var e,t;this.localTracks.size===0&&ir()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],$t.prototype,"unpublish",1),N([ba(e=>{if(e.code!==S.API_CALL_ABORTED)throw e}),Li(e=>e.userId)],$t.prototype,"replaceTrack",1),N([Li((...e)=>e[0].userId),Ma(),cp(),ht({settings:{retries:gi,timeout:e=>Nt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(I.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],$t.prototype,"subscribe",1),N([Uo({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),Li((...e)=>e[0].userId)],$t.prototype,"unsubscribe",1);nn.create=nn._create.bind(nn,$t);var c$=nn;export{c$ as default};
131
+ next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:h,direction:u,stopped:m})=>({mid:l,currentDirection:h,direction:u,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(d)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return A(this,null,function*(){if(!Ue||!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===ke.INACTIVE&&n===ke.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===ke.SENDONLY&&n===ke.INACTIVE&&(this._parsedAnswer.media[o].direction=ke.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return et(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=I_(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 A(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===S.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=[],Gs(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return A(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];M(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===S.VIDEO){let d;e&&this.is42001fSupported?d=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(d=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),d&&!((a=n.payloads)!=null&&a.includes(String(d.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Gs(n,d),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Pi(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var h;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let d=Math.floor(o/r),l=(this._isRelayTried||d>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${d} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return A(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`),Q.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),Q.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};J([Vd("reconnect")],vi.prototype,"startReconnection",1),J([br(e=>e.userId)],vi.prototype,"addDownlink",1),J([br(e=>e)],vi.prototype,"removeDownlink",1),J([Xi(!0)],vi.prototype,"updateSDP",1),J([zt(521712,!1)],vi.prototype,"setOffer",1),J([zt(521713,!1)],vi.prototype,"setAnswer",1);var om=class{constructor(i){c(this,"tag");c(this,"len");c(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},nm=class{constructor(i){c(this,"tinyId");c(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new om(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},v_=new Set;function Ws(){let s=Math.floor(Math.random()*4294967296);return v_.has(s)?Ws():(v_.add(s),s)}var O_=gt(Mt());var zs=class extends O_.default{constructor(e){super();c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_currentState","DISCONNECTED");c(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=z.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:(x.emit(B.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 Ta=class extends zs{constructor(e){super(de(Z({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});c(this,"_flag",0);c(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:d}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:d||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${gr()} ${Ts()}`),Q.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Le.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Le.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&&(Hi()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===S.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=Z({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&Hr),bigVideo:!!(this.flag&Fr),smallVideo:!!(this.flag&rn),auxVideo:!!(this.flag&ds)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,h,u,m,p,g,f;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new X({code:H.NOT_SUPPORTED_H264,message:pe({key:me.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),ze&&uo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(si["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let d;if(t&&!r&&t.small&&(d=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:ve.SPC_PUBLISH,responseCommand:Ee.SPC_PUBLISH_RESULT,data:de(Z({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:d,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:T}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],T,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(p=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:p.bitrate,auxVideo:(g=this.localAuxVideoTrack)==null?void 0:g.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(f=this._room.scheduleResult.config)!=null&&f.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!Yt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,d=this._peerConnection.getTransceivers(),l=[],h=[],u=(p,g,f)=>{var I,v;let T=d[g].sender.replaceTrack(f);h.push(g),(I=this.singlePC)!=null&&I.enableInsertableStreams&&T.then(()=>this.createEncodedStreams(d[g].sender,p)),(v=this.singlePC)!=null&&v.scriptTransformWorker&&this.initSenderTransfrom(d[g].sender,p),l.push(T)};a&&u(e.mediaType,0,a),n&&u(t.mediaType,o?3:1,n),r&&u(8,2,r);let m=this.singlePC.setTransceiverDirection(ke.SENDONLY,h);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,d;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((d=this.getTrackByMediaType(t))!=null&&d.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,h)=>{var m;let u=this.getTrackByMediaType(t);h.enqueue((m=this.singlePC)!=null&&m.isUsingH264&&u?u.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return A(this,null,function*(){var r;if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:o}=t[2];(r=this.singlePC)!=null&&r.enableInsertableStreams&&this.createEncodedStreams(o,8),yield o.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(ke.SENDONLY,[2])}}else yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ke.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 A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();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=de(Z({},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=de(Z({},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(ke.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 A(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:ve.PUBLISH_STATE_CHANGE,data:t,responseCommand:Ee.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ve.UNPUBLISH,commandDesc:"unpublish",responseCommand:Ee.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===H.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),Gi){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:ve.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Ee.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return A(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?S.AUXILIARY:S.MAIN} stream`),Hi()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return A(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===S.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ke.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ke.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return A(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?S.AUXILIARY:S.MAIN} stream`),Hi()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return A(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===S.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(ke.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return A(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?S.AUXILIARY:S.MAIN} stream`),r.kind===S.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===S.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return A(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===S.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:ve.UPDATE_MUTE_STAT,responseCommand:Ee.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&x.emit(B.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=S.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===S.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===S.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===S.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===S.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===cs?(this._log.error(Tt.NOT_SUPPORTED_H264ENCODE),new X({code:H.NOT_SUPPORTED_H264,message:pe({key:me.NOT_SUPPORTED_H264ENCODE})})):new X({code:H.UNKNOWN,message:pe({key:me.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ee.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return A(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}))})}};J([Ut(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],Ta.prototype,"publish",1),J([Ut(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],Ta.prototype,"unpublish",1);var am=Ta;function w_(s){return Object.keys(s).filter(i=>s[i])}var Go=class extends zs{constructor(e){super(de(Z({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});c(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ci(this._room,this),this.remoteVideoTrack=new er(this._room,this),this.remoteAuxiliaryTrack=new Do(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 ur(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===S.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var h,u;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let d=S.AUDIO;r.kind===S.VIDEO&&(d=a===S.MAIN?S.VIDEO:S.AUXILIARY);let l=this.remoteAudioTrack;d===S.VIDEO?l=this.remoteVideoTrack:d===S.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(h=this.singlePC)==null||h.receiverRemoteTrackMap.set(o,l),(u=this.singlePC)!=null&&u.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===S.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var d,l;let a=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let d=o.enqueue(n);d&&a.enqueue(d)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return A(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${w_(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 X({code:H.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"),xt&&qt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return A(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=Z({},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} [${w_(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=ve.UNSUBSCRIBE,n=Ee.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=ve.SUBSCRIBE_CHANGE,n=Ee.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let d=new X({code:a.code,message:pe({key:me.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return A(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return A(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:Ws(),bigVideoSsrc:Ws(),bigVideoRtxSsrc:Ws(),auxVideoSsrc:Ws(),auxVideoRtxSsrc:Ws()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:d,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:d,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:ve.SPC_SUBSCRIBE,responseCommand:Ee.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(h.data.code!==0)throw new X({code:h.data.code,message:h.data.message})}catch(h){throw yield this.removeDownlink(),h}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!Id)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(De(n)||De(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return A(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Id||!this.singlePC||!this._peerConnection||pr(e)&&pr(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return De(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),De(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,pr(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var u;let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack||pr(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(d&&pr(t)||!d&&pr(e))return;let l=d?t||0:e,h=(a.jitterBufferTarget||0)+100;h>l||(a.jitterBufferTarget=h,this._log.debug(`set ${d?"aux ":""}${(u=a==null?void 0:a.track)==null?void 0:u.kind} jitterBuffer delay ${h} -> ${l}`))}),!r.find(a=>{let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};J([Xi(),be(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Go.prototype,"subscribe",1),J([Xi()],Go.prototype,"unsubscribe",1),J([br(()=>"jitter")],Go.prototype,"setJitterBufferDelay",1);var M_=Go;function x_(){return be(s=>function(...i){return A(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;x.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function L_(){return be(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var P_=gt(Mt());function XS(){return Math.floor(Math.random()*16383)}var zc=class zc extends P_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;c(this,"log");c(this,"cmdIdSeqMap",new Map);c(this,"messageMap",new Map);this.log=z.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(Ee.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)||XS(),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(ve.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)>zc.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),hr(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let d=[...r.cachedMessageMap.values()].sort((l,h)=>l.message.seq-h.message.seq);d[0]&&(o=d[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};c(zc,"SEQ_INTERVAL",300);var Wc=zc;var{isString:U_,isUndefined:Wo,getNetworkType:QS,isEmpty:Sa}=Jt,Ni=class extends Hc{constructor(e){super(e);c(this,"_businessInfo");c(this,"userManager");c(this,"_version");c(this,"_heartbeat",-1);c(this,"_lastHeartBeatTime",-1);c(this,"_stats");c(this,"_joinTimeout",-1);c(this,"_firstPublishedList",null);c(this,"_joinReject",null);c(this,"_isRelayChanged",!1);c(this,"sdpSemantics");c(this,"signalChannel",null);c(this,"uplinkConnection",null);c(this,"singlePC",null);c(this,"enableSPC",go);c(this,"_changeBigSmallRecords",new Map);c(this,"networkQuality");c(this,"_iceTransportPolicy");c(this,"forceRelay",!1);c(this,"_turnServers",[]);c(this,"_iceServersFromJoin");c(this,"_syncUserListInterval",-1);c(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});c(this,"enableSEI",!1);c(this,"_enableAudioVolumeEvaluation",!1);c(this,"_audioVolumeIntervalId",0);c(this,"_enableMultiAuxStream",!1);c(this,"_pureAudioPushMode",!1);c(this,"_customMessageManager");c(this,"preferHW",!1);c(this,"healthDetector");c(this,"playoutDelay");c(this,"jitterBufferDelay");c(this,"_updateAudioLevelTaskId",-1);this._stats=new _a(this,this._log),this.userManager=new rc(this.userId,this._log),this._version=Rt,this.sdpSemantics=Js,Wo(e.sdpSemantics)?Wi.isUnifiedPlanDefault()&&(this.sdpSemantics=Gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${QS()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Wo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&go,!Wo(e.enableSPC)&&go&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new C_(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 A(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=mm(n,[]);x.emit(B.REMOTE_PUBLISH_STATE_CHANGED,Z({room:this},o)),this.emit("remote-publish-state-changed",Z({},o))}),this.joinParams=e,new Promise((o,n)=>A(this,null,function*(){var a,d;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(h){if(h instanceof X&&h.code===H.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let l=le();yield this.doJoin(e,(d=this.singlePC)==null?void 0:d.clientAbility),Q.addSuccessEvent({key:521708,cost:le()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){Q.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return A(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new vi({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new X({code:H.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>A(this,null,function*(){var d,l,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(rt.SETUP_FAILED,u=>{this.clearJoinTimeout(),x.emit(B.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),o(u)}),Qe((l=(d=this.scheduleResult)==null?void 0:d.config)==null?void 0:l.singlePC)&&go&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ml(),netType:ps(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(h=this.scheduleResult.config)!=null&&h.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new X({code:H.JOIN_ROOM_FAILED,message:pe({key:me.JOIN_ROOM_TIMEOUT})}))},a),x.emit(B.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?ve.SPC_JOIN_ROOM:ve.JOIN_ROOM,n),this.signalChannel.once(Ee.JOIN_ROOM_RESULT,u=>A(this,null,function*(){this.clearJoinTimeout();let{code:m,message:p,data:g,tinyId:f}=u.data;x.emit(B.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),f&&(this.tinyId=f),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var T;(T=this.singlePC)==null||T.connect(de(Z({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${p}`),o(new X({code:H.JOIN_ROOM_FAILED,extraCode:m,message:pe({key:me.JOIN_ROOM_FAILED,data:{error:p,code:m}})})))}))}))}reJoin(){return A(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(de(Z({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),Me.logSuccessEvent({userId:this.userId,eventType:Ft.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(sr.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof am&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(sr.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof fa&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),Me.logFailedEvent({userId:this.userId,eventType:Ft.REJOIN,error:e}),this.emit("error",new X({code:H.JOIN_ROOM_FAILED,message:pe({key:me.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return A(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Qf(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new Vo({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Wc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ho({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ho.EVENT_NETWORK_QUALITY,a=>{var d;this.emit("network-quality",a),(d=this.singlePC)==null||d.detectTCPAndUDP(a)})),vt(this,this.signalChannel).add(rt.CONNECTION_STATE_CHANGED,a=>{x.emit(B.SIGNAL_CONNECTION_STATE_CHANGED,Z({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(rt.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(Ee.PEER_JOIN,a=>{let{srcTinyId:d,userId:l,role:h}=a.data.data;this.userManager.addUser({userId:l,tinyId:d,role:h})}).add(Ee.PEER_LEAVE,a=>{let{userId:d,reason:l=0}=a.data.data;this.userManager.deleteUser(d,l)}).add(Ee.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(Ee.CLIENT_BANNED,a=>{let d=a.data.data,{reason:l}=d;if(Me.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}),this.signalChannel.once(rt.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,x.emit(B.JOIN_SIGNAL_CONNECTION_END,{room:this})}),x.emit(B.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&x.emit(B.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||at(this)}leave(){return A(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),x.emit(B.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(ve.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=Le.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Le.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return A(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?rf(this.userId):[],o=de(Z({str_sdk_version:Ko,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:Z({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:ps()},t.msg_device_info)});if(this.heartbeatReport=o,x.emit(B.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(ve.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",de(Z({},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!==il).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})}),x.emit(B.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 fa&&(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?M_:Qh)({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!==H.ICE_TRANSPORT_ERROR&&(o===H.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",de(Z({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Le.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){Le.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:ve.GET_USER_LIST,responseCommand:Ee.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:d,role:l})=>({userId:a,tinyId:d,role:l}));throw pe({key:me.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ee.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||!Wh)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)===Je.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof $t&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===Je.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return A(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Me.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new fa({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 Qh({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 X({code:H.INVALID_OPERATION,message:pe({key:me.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),Le.clearTask(this._audioVolumeIntervalId))}switchRole(e){return A(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:ve.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:Ee.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 X({code:H.SWITCH_ROLE_FAILED,message:pe({key:me.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof X&&r.getCode()===H.API_CALL_TIMEOUT&&(r=new X({code:H.SWITCH_ROLE_FAILED,message:pe({key:me.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return A(this,null,function*(){let t={},r={};e.forEach(d=>{d instanceof ti&&(d instanceof Yi?r.audio=d:t.audio=d),d instanceof Nt&&(d instanceof jt&&d.mediaType===2?r.video=d:t.video=d)});let o=Sa(t),n=Sa(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new am({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new fa({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",de(Z({},d),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",d=>{let l=d.getCode();l!==H.ICE_TRANSPORT_ERROR&&(l===H.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",d))}));let a=e.map(d=>d.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return A(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 ti&&(o instanceof Yi?r.audio=o:t.audio=o),o instanceof Nt&&(o instanceof jt&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Sa(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Sa(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||!iu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&x.emit(B.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return A(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return A(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:S.VIDEO,videoType:S.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return A(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=Z({},r.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),x.emit(B.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${xc(n)}] prev: [${xc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());x.emit(B.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof X?n.getCode():H.UNKNOWN,d=n;throw n instanceof X?a===H.REMOTE_STREAM_NOT_EXIST&&(d=new X({code:H.API_CALL_ABORTED,message:pe({key:me.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(d)):(d=new X({code:a,message:pe({key:me.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(d)),d}})}unsubscribe(...e){return A(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)}),x.emit(B.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,Le.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),x.emit(B.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Le.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Le.run("intervalInWorker",()=>{var o;bs.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!bs.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return A(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=Le.run("intervalInWorker",()=>A(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:d}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(d.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Le.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(!ru||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;De(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&De(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return A(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 A(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 A(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 A(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 A(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(Jt.getTurnServer(o))):Jt.isPlainObject(e)&&r.push(Jt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:ve.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:Ee.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:ve.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:Ee.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?ve.START_PUBLISH_TENCENT_CDN:ve.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?Ee.START_PUBLISH_TENCENT_CDN_RES:Ee.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?ve.STOP_PUBLISH_TENCENT_CDN:ve.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?Ee.STOP_PUBLISH_TENCENT_CDN_RES:Ee.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:ve.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:Ee.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:ve.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:Ee.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:ve.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:Ee.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:ve.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:Ee.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Jt.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 A(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:d,reSubscribeCount:l}=a;if(d.video&&t.video||d.smallVideo&&t.smallVideo&&o)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:d.video,smallVideo:d.smallVideo};try{if(!o&&h.smallVideo&&(h.video=!0,h.smallVideo=!1),h.smallVideo===t.smallVideo&&h.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(h,"main"),e.remoteVideoTrack.setMediaType(h.smallVideo?8:4),this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video successfully. count ${qs-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=qs}catch(u){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${qs-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:qs};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(U_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Wo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new X({code:H.INVALID_PARAMETER,message:pe({key:me.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(!Wo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new X({code:H.INVALID_PARAMETER,message:pe({key:me.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Wo(e.userDefinePushArgs))if(U_(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 X({code:H.INVALID_PARAMETER,message:pe({key:me.INVALID_USER_DEFINE_PUSH_ARGS})});Sa(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return A(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ar)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new X({code:H.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}};J([qe(["left",ge.INIT],"joined"),Gt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),yi(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),zf()],Ni.prototype,"join",1),J([qe("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),jf(),Vd("leave room"),$n({fnName:"publish",validateArgs:!1}),$n({fnName:"unsubscribe",validateArgs:!1})],Ni.prototype,"leave",1),J([Xi(),x_(),Gt({settings:{retries:dr,timeout:e=>pi(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),x.emit(B.PUBLISH_FAILED,{room:this}))}})],Ni.prototype,"publish",1),J([$n({fnName:"publish"}),Hp("api-call"),Xi(),L_(),Ut(function(){var e,t;this.localTracks.size===0&&Qr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ni.prototype,"unpublish",1),J([Ld(e=>{if(e.code!==H.API_CALL_ABORTED)throw e}),br(e=>e.userId)],Ni.prototype,"replaceTrack",1),J([br((...e)=>e[0].userId),Fd(),Jf(),Gt({settings:{retries:dr,timeout:e=>pi(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),x.emit(B.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],Ni.prototype,"subscribe",1),J([$n({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),br((...e)=>e[0].userId)],Ni.prototype,"unsubscribe",1);ma.create=ma._create.bind(ma,Ni);var JH=ma;export{JH as default};
132
+ /*! Bundled license information:
133
+
134
+ jszip/dist/jszip.min.js:
135
+ (*!
136
+
137
+ JSZip v3.10.1 - A JavaScript class for generating and reading zip files
138
+ <http://stuartk.com/jszip>
139
+
140
+ (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
141
+ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
142
+
143
+ JSZip uses the library pako released under the MIT license :
144
+ https://github.com/nodeca/pako/blob/main/LICENSE
145
+ *)
146
+ */